Query Expression的排序與聚合函數範例

  • 554
  • 0

Query Expression的排序與聚合函數範例

        {
            List<Test> list = new List<Test>
            {   
                new Test{Id=0,name="K",value="005"},
                new Test{Id=1,name="C",value="004"},
                new Test{Id=2,name="K",value="003"},
                new Test{Id=3,name="C",value="002"},
                new Test{Id=4,name="K",value="001"},
                new Test{Id=5,name="C",value="000"}                
            };

            list.Sort((x,y)=>string.Compare(x.value,y.value));
            IEnumerable<KeyValuePair<string, string>> list2 = list.GroupBy(g => g.name).Select(x => new KeyValuePair<string, string>(x.Key, x.Max(g => g.value)));
            KeyValuePair<string, string> kvp = list2.First();
            return Content(kvp.Key + " " + kvp.Value);
        }

 

參考資料來源:

[1]C# List<> OrderBy Alphabetical Order
http://stackoverflow.com/questions/188141/c-sharp-list-orderby-alphabetical-order

[2]GroupBy in lamda expressions
http://stackoverflow.com/questions/3101824/groupby-in-lamda-expressions

[3]How to: Group Query Results (C# Programming Guide)
http://msdn.microsoft.com/en-us/library/bb545971.aspx