C# LINQ counting elements with DISTINCT

十年热恋 提交于 2019-11-28 04:14:09

问题


I have a collection of KeyValuePair items with DateTime as key and a string as value. Basically my data looks like:

12/07/2013 - 10220
12/07/2013 - 10220
12/07/2013 - 12220
12/07/2013 - 11240
12/07/2013 - 15220
13/07/2013 - 23220
13/07/2013 - 35620
14/07/2013 - 15620
14/07/2013 - 15620

I would like to have a List of how many items (distinct) I've for each days. So the query would result in a:

12/07/2013 - 4
13/07/2013 - 2
14/07/2013 - 1

回答1:


use group by

var dateGrouped = dates.GroupBy(x => x.Key)
                       .Select(x => new { Date = x.Key, Values = x.Distinct().Count() });



回答2:


Below is the solution with complete example

        var list = new[]
        {
            new {Date = new DateTime(2013,07,12), value = 10220},
            new {Date = new DateTime(2013,07,12), value = 10220},
            new {Date = new DateTime(2013,07,12), value = 12220},
            new {Date = new DateTime(2013,07,12), value = 11240},
            new {Date = new DateTime(2013,07,12), value = 15220},
            new {Date = new DateTime(2013,07,13), value = 23220},
            new {Date = new DateTime(2013,07,13), value = 35620},
            new {Date = new DateTime(2013,07,14), value = 15620},
            new {Date = new DateTime(2013,07,14), value = 15620},
        };


        var res = from l in list group l by new { l.Date } into g select new { g.Key.Date, value = g.Distinct().Count() };

        foreach (var item in res)
        {
            Console.WriteLine(item.Date + " " + item.value);
        }


来源:https://stackoverflow.com/questions/17652301/c-sharp-linq-counting-elements-with-distinct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!