如何编写使用MVC强类型的模型DISTINCT或GROUPBY LINQ声明 [英] How to write a DISTINCT or GROUPBY LINQ statement using a strongly typed model in MVC
本文介绍了如何编写使用MVC强类型的模型DISTINCT或GROUPBY LINQ声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为作为调查重点如下型号;
I have a Model called Survey as highlighted below;
我想要写在我的控制器中的LINQ语句,将查询率调查表和主题返回不同的记录。每个不同的记录将有平均评分。例如;
I want to write a LINQ statement in my controller that will query the Survey Table and return distinct records by 'Topic'. Each distinct record will have an average rating. For example;
我是新来的LINQ和有创造什么,是不是基本的,当一个困难时期。
I'm new to LINQ and have a hard time when creating anything that is not basic.
我的企图;
var results = from s in db.Surveys
where s.Topic.Distinct()
select new Survey
{
SurveyId = s.SurveyId,
Category = s.Category.Name,
Topic = s.Topic,
Store1Rating= db.Surveys.Average(s => s.Score1).Value,
Store2Rating= db.Surveys.Average(s => s.Score2).Value
};
感谢您的帮助提前!
Thanks for your help in advance!
推荐答案
试试这个
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var survey1 = new Survey() { Topic = "topic1", Store1Rate = 5, Store2Rate = 4 };
var survey2 = new Survey { Topic = "topic2", Store1Rate = 6, Store2Rate = 2 };
var survey3 = new Survey { Topic = "topic2", Store1Rate = 7, Store2Rate = 2 };
var survey4 = new Survey { Topic = "topic3", Store1Rate = 6, Store2Rate = 4 };
var survey5 = new Survey { Topic = "topic3", Store1Rate = 1, Store2Rate = 2 };
var survey6 = new Survey { Topic = "topic3", Store1Rate = 2, Store2Rate = 9 };
List<Survey> surveys = new List<Survey>() { survey1, survey2, survey3, survey4, survey5, survey6 };
var result = surveys.GroupBy(s => s.Topic).Select(s => new { Topic = s.Key, Rate1 = s.Average(a => a.Store1Rate), Rate2 = s.Average(a => a.Store2Rate) });
}
}
class Survey
{
public string Topic;
public int Store1Rate;
public int Store2Rate;
}
}
这篇关于如何编写使用MVC强类型的模型DISTINCT或GROUPBY LINQ声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文