C# 基于字段字符串的不同记录比较、平均字段并返回动态对象

C# 基于字段字符串的不同记录比较、平均字段并返回动态对象,c#,.net,linq,C#,.net,Linq,我使用的是MVC5,其中我有以下模型/表格,称为问题 我想产生以下结果 我的目标是获得反映不同主题的记录列表,以及给定不同主题的所有分数的平均值 var result = from q in db.Questions where q.Topic.Distinct() select new Question { Category = q.Category,

我使用的是MVC5,其中我有以下模型/表格,称为问题

我想产生以下结果

我的目标是获得反映不同主题的记录列表,以及给定不同主题的所有分数的平均值

var result = from q in db.Questions
               where q.Topic.Distinct()
              select new Question
              {
                  Category = q.Category,                             
                  Topic = q.Topic,                              
                  Store1Rating = db.Questions.Where(x => x.Topic == q.Topic).Average(s1 => s1.Store1Rating).ToString(),
                  Store2Rating = db.Questions.Where(x => x.Topic == q.Topic).Average(s2 => s2.Store2Rating).ToString()
              };

我知道我离LINQ声明还有一段距离,但我只有大约6周的时间来做基本的LINQ声明。对我来说,这是比基本LINQ更复杂的另一层。提前谢谢

您可以使用
GroupBy

var result = db.Questions.GroupBy(x => new
//grouping data by category and topic, rows which have same category and topic will be in a group
{
    x.Category,
    x.Topic
}).Select(g => new
//now selecting category and topic for each group and the data we want
{
    g.Key.Category,
    g.Key.Topic,
    //calculate Store1Rating average of all rows which has same category and topic as this group
    Store1Rating = db.Questions.Where(x => x.Category == g.Key.Category && x.Topic == g.Key.Topic).Average(x => x.Store1Rating),
    //calculate Store2Rating average of all rows which has same category and topic as this group
    Store2Rating = db.Questions.Where(x => x.Category == g.Key.Category && x.Topic == g.Key.Topic).Average(x => x.Store2Rating),
});

请尝试下面的代码。请参考以下网页:

使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用系统数据;
命名空间控制台应用程序1
{
班级计划
{
静态void Main(字符串[]参数)
{
DataTable问题=新建DataTable();
问题。列。添加(“Id”,类型(int));
问题。列。添加(“类别”,类型(字符串));
问题。列。添加(“主题”,类型(字符串));
问题。列。添加(“Store1Rating”,typeof(int));
问题。列。添加(“Store2Rating”,typeof(int));
添加(新对象[]{1,“食物”,“比萨饼”,5,6});
添加(新对象[]{2,“食物”,“比萨饼”,4,5});
添加(新对象[]{3,“食品”,“冰淇淋”,4,5});
添加(新对象[]{4,“饮料”,“啤酒”,3,4});
添加(新对象[]{5,“饮料”,“苏打”,4,5});
添加(新对象[]{6,“食物”,“比萨饼”,5,6});
添加(新对象[]{7,“食物”,“比萨饼”,4,5});
添加(新对象[]{8,“食品”,“冰淇淋”,3,4});
添加(新对象[]{9,“饮料”,“啤酒”,4,5});
添加(新对象[]{10,“饮料”,“苏打”,5,6});
var summary=问题。可计算()
.GroupBy(x=>x.Field(“主题”))
.选择(x=>new
{
id=x.FirstOrDefault().Field(“id”),
category=x.FirstOrDefault().Field(“category”),
topic=x.键,
评级1=x.Select(y=>y.Field(“Store1Rating”).ToList().Average(),
评级2=x.Select(y=>y.Field(“Store2Rating”).ToList().Average()
}).ToList();
}
}
}
​

太棒了!现在你能解释一下发生了什么事吗关于如何学习LINQ>基础的任何建议。我添加了一些评论。你可以从以下错误开始学习;传入字典的模型项的类型为“System.Collections.Generic.List
1[f_uAnonymousType7
7[Question.Models.Category,System.String,System.Int32,System.Int32,System.String,System.Double,System.Double]],但此字典需要类型为“System.Collections.Generic.IEnumerable`1[Question.Models.Questions]的模型项“。这是因为
result
中的项类型是匿名的,但您正试图将它们添加到另一类型的词典中。确定。我使用的是MVC,上面的逻辑在我的控制器中,我使用的是一个名为Question的模型。我想从数据库中检索记录,并将模型移交给视图。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable Questions = new DataTable();

            Questions.Columns.Add("Id", typeof(int));
            Questions.Columns.Add("Category", typeof(string));
            Questions.Columns.Add("Topic", typeof(string));
            Questions.Columns.Add("Store1Rating", typeof(int));
            Questions.Columns.Add("Store2Rating", typeof(int));

            Questions.Rows.Add(new object[] { 1,"Food","Pizza", 5, 6 });
            Questions.Rows.Add(new object[] { 2, "Food", "Pizza", 4, 5 });
            Questions.Rows.Add(new object[] { 3, "Food", "Ice Cream", 4, 5 });
            Questions.Rows.Add(new object[] { 4, "Beverage", "Beer", 3, 4 });
            Questions.Rows.Add(new object[] { 5, "Beverage", "Soda", 4, 5 });
            Questions.Rows.Add(new object[] { 6, "Food", "Pizza", 5, 6 });
            Questions.Rows.Add(new object[] { 7, "Food", "Pizza", 4, 5 });
            Questions.Rows.Add(new object[] { 8, "Food", "Ice Cream", 3, 4 });
            Questions.Rows.Add(new object[] { 9, "Beverage", "Beer", 4, 5 });
            Questions.Rows.Add(new object[] { 10, "Beverage", "Soda", 5, 6 });

            var summary = Questions.AsEnumerable()
                .GroupBy(x => x.Field<string>("Topic"))
                .Select(x => new
                {
                    id = x.FirstOrDefault().Field<int>("Id"),
                    category = x.FirstOrDefault().Field<string>("Category"),
                    topic = x.Key,
                    rating1 = x.Select(y => y.Field<int>("Store1Rating")).ToList().Average(),
                    rating2 = x.Select(y => y.Field<int>("Store2Rating")).ToList().Average()
                }).ToList();
        }
    }
}
​