当前位置: 首页 > 编程语言 > C#

LambB表达式中的GroupBy分享

时间:2023-04-10 21:06:37 C#

GroupByinLambBexpressionfromxinmyCollectiongroupxbyx.Idintoyselectnew{Id=y.Key,Quantity=y.Sum(x=>x.Quantity)};你会如何将上面的代码写成lambda表达式?我被困在groupinto。查询串联(select...into和group...into,但不是join...into)等同于只拆分查询表达式。所以我想将您的示例视为:vartmp=fromxinmyCollectiongroupxbyx.Id;varresult=fromyintmpselectnew{Id=y.Key,Quantity=y.Sum(x=>x.Quantity)};将它们更改为点符号:vartmp=myCollection.GroupBy(x=>x.Id);varresult=tmp.Select(y=>new{Id=y.Key,Quantity=y.Sum(x=>x.Quantity)});然后你可以将它们组合在一起:vartmp=myCollection.GroupBy(x=>x.Id).Select(y=>new{Id=y.Key,Quantity=y.Sum(x=>x.Quantity)});一旦弄清楚C#编译器对查询表达式做了什么,剩下的就相对简单了:)myCollection.GroupBy(x=>x.Id).Select(y=>new{Id=y.Key,Quantity=y.Sum(x=>x.Quantity)});myCollection.GroupBy(x=>x.Id).Select(x=>new{Id=x.Key,Quantity=x.Sum(y=>x.Quantity});varmostFrequent=lstIn.Where(i=>!string.IsNullOrEmpty(i)).GroupBy(s=>s).OrderByDescending(g=>g.Count()).Select(s=>s.Key).FirstOrDefault();所以这里的大部分答案每个人似乎都在处理从组的计数中获取Id的简单对象,而Key本身就是组.Key。虽然这可能是这个的主要用途。并不能真正满足我的需求。对于我自己的情况,我基本上想按某些对象属性进行分组,然后从该组中获取特定对象。这是一个示例代码。使用系统;使用System.Collections.Generic;使用System.Linq;公共类程序{publicstaticvoidMain(){Console.WriteLine("HelloWorld");varresponse=newList();varlistOfStudents=newList();//将一些对象插入到listOfStudents对象中。listOfStudents.GroupBy(g=>g.Class).ToList().ForEach(g=>response.Add(g.OrderByDescending(s=>s.CreatedOn).Select(a=>newResponseClass{SName=a.StudentName,SAge=a.Age,SClass=a.Class,SCreatedOn=a.CreatedOn,RandomProperty=Guid.NewGuid().ToString()}).First()));Console.WriteLine("这编译并且应该工作得很好");}classStudent{publicstringStudentName{get;放;}publicintAge{得到;放;}公共字符串类{得到;放;}publicDateTimeCreatedOn{get;放;}}classResponseClass{publicstringSName{get;放;}publicintSAge{得到;放;}publicstringSClass{得到;放;}publicDateTimeSCreatedOn{get;放;}公共字符串RandomProper泰{得到;放;如果你更愿意使用foreach循环(我更喜欢lambdas因为我觉得它更容易阅读),但如果你这样做,你可以做foreach(IGroupinggroupedStudentsinlistOfStudents.GroupBy(g=>g.Class)){response.Add(groupedStudents.OrderByDescending(x=>x.CreatedOn).Select(a=>newResponseClass{SName=a.StudentName,SAge=a.Age,SClass=a.Class,SCreatedOn=a.CreatedOn,RandomProperty=Guid.NewGuid().ToString()}).First());希望这对某人有帮助。?以上就是C#学习教程:LambB表达式中的GroupBy分享的全部内容。侵权请点击右侧联系管理员删除。如需转载请注明出处: