C#GroupBy、Sum、Select组合使用

网友投稿 265 2022-09-05

C#GroupBy、Sum、Select组合使用

List result = new List(); mesStocks.GroupBy(x => new { x.Deid, x.Pno, x.Sno }, (x, y) => { var total = y.Sum(a => a.TotalNums); var res = y.Select(stock => { stock.TotalNums = total; return stock; }).ToList(); result.Add(res.First()); return res; }).ToList();

测试代码:

static void Main(string[] args) { var test = new List { new MesStock { Deid="1",Pno="1",Sno="1",TotalNums=1}, new MesStock { Deid="1",Pno="1",Sno="1",TotalNums=1}, new MesStock { Deid="1",Pno="1",Sno="1",TotalNums=11}, new MesStock {Deid="2",Pno="2",Sno="2",TotalNums=2}, new MesStock {Deid="2",Pno="2",Sno="2",TotalNums=2}, new MesStock {Deid="2",Pno="2",Sno="2",TotalNums=33}, new MesStock {Deid="3",Pno="3",Sno="3",TotalNums=3}, }; List res = new List(); test.GroupBy(x => x.Deid + x.Pno + x.Sno, (x, y) => { var total = y.Sum(a => a.TotalNums); var tt = y.Select(t => { t.TotalNums = total; return t; }).ToList(); res.Add(tt.First()); return tt; }).ToList(); foreach (var item in res) { Console.WriteLine(item.TotalNums); } }

public static class GroupHelper { public static List> Group(this List source, Func, bool> limitFunc) { return Group(source, limitFunc); } public static List> Group(this List source, Func, bool> limitFunc) { var result = new List>(); List resItem = null; var inter = source.GetEnumerator(); foreach (var item in source) { if (resItem == null) resItem = new List(); resItem.Add(item); if (limitFunc(resItem.ToList())) { resItem.Remove(item); result.Add(resItem); resItem = new List { item }; } } return result; } public class t { public string key { get; set; } } public static object test() { var list = new List { new t { key = "b" }, new t { key = "c" },new t { key = "b" }, new t { key = "a" },new t { key = "c" },new t { key = "e6" }, new t { key = "e9" }, new t { key = "c" }, new t { key = "e1" }, new t { key = "e4" },new t { key = "e7" },new t { key = "e10" }, new t { key = "b" },new t { key = "e5" },new t { key = "e8" },new t { key = "e11" }, new t { key = "e3" }, new t { key = "e13" },new t { key = "a" },new t { key = "e2" },new t { key = "e12" }, }; var res = list.GroupBy(m => m.key).OrderByDescending(m => m.Count()).SelectMany(m => m).ToList(); return res.Select(m => m.key); //"b", "b", "b", "c", "c", "c", "a", "a", "e6", "e9", "e1", "e4", "e7", "e10", "e5", "e8", "e11", "e3", "e13", "e2", "e12" //var source = "a a b b b c c c d d e1 e2 e3 e4 e5 e6 e7 e8 e9 e10 e11 e12 e13".Split(' ').ToList(); //var groups = source.Group(r => (!(r.Count == 2 && r.Distinct().Count() == 2) && r.Count > 1 && r.Distinct().Count() == 2) || (r.Count == 13 && r.Distinct().Count() == 13)); //return groups; //result: //aa //bbb //ccc //dd //e1-e12 //e13 } }

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:营销案例精选:鸿星尔克到底有多清醒?
下一篇:C# Elasticsearch帮助类
相关文章

 发表评论

暂时没有评论,来抢沙发吧~