简体   繁体   English

如何计算按嵌入式列表分组的列表项

[英]How to count list items grouped by an embedded list

I have a class like 我有一个像

class MyClass
{
    public DateTime Date { get; set; }
    public List<int> IdList { get; set; }

    public MyClass(DateTime initDate)
    {
        Date = initDate;
        IdList = new List<int>();
    }
}

and need to count the number of entries in a List<MyClass> , grouped by each int in IdList . 并且需要计算List<MyClass>的条目数,该条目由IdList的每个int分组。

I have experimented with various Linq constructs, but I cannot get anything to work. 我已经尝试了各种Linq构造,但是我什么都无法工作。 Here is what I have so far: 这是我到目前为止的内容:

List<MyClass> myc = new List<MyClass>();
myc.Add(new MyClass(new DateTime(2016, 1, 1)) { IdList = new List<int> { 1, 2 } });
myc.Add(new MyClass(new DateTime(2016, 1, 2)) { IdList = new List<int> { 1, 3 } });
myc.Add(new MyClass(new DateTime(2016, 1, 3)) { IdList = new List<int> { 1, 4 } });
myc.Add(new MyClass(new DateTime(2016, 1, 4)) { IdList = new List<int> { 5, 6 } });
myc.Add(new MyClass(new DateTime(2016, 1, 5)) { IdList = new List<int> { 2, 3 } });

var grouped = from p in myc
    group p by p.IdList into g
    select new { Id = g.Key, Count = g.Count() };
foreach (var x in grouped)
{
    Console.WriteLine("ID: {0}, Count: {1}", x.Id, x.Count);
}

// Expecting output like:
// ID: 1, Count: 3
// ID: 2, Count : 2
// etc.

If there was a single int Id property in MyClass , it would be straightforward, but I cannot work out how to use the List<int> . 如果MyClass只有一个int Id属性,那将很简单,但是我无法弄清楚如何使用List<int> Is there any alternative to writing nested loops and populating a Dictionary? 除了编写嵌套循环和填充字典之外,还有其他选择吗? Thanks for any help. 谢谢你的帮助。

You can use SelectMany 您可以使用SelectMany

var grouped = myc.SelectMany(x => x.IdList).GroupBy(x => x);
foreach (var i in g)
{
    Console.WriteLine(string.Format("Id: {0}, Count: {1}", i.Key,i.Count()));
}

This should give you the output you're looking for. 这应该为您提供所需的输出。

I don't know if I've understand your requeriment correctly. 我不知道我是否正确理解了您的要求。 But try this and let me know: 但是尝试一下,让我知道:

var groupedIds = myc.SelectMany(x => x.IdList.Select(i => i))
    .GroupBy(x => x)
    .ToList();

The full fiddle here 完整的小提琴在这里

And here SelectMany documentation so you know what this code means. 在这里, SelectMany文档使您知道此代码的含义。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM