我有一个像
class MyClass
{
public DateTime Date { get; set; }
public List<int> IdList { get; set; }
public MyClass(DateTime initDate)
{
Date = initDate;
IdList = new List<int>();
}
}
并且需要计算中的条目数List<MyClass>
,并按中的每组int
进行分组IdList
。
我已经尝试了各种Linq构造,但是我什么都做不了。这是我到目前为止的内容:
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.
如果其中只有一个int Id
属性MyClass
,那将很简单,但是我无法弄清楚如何使用List<int>
。除了编写嵌套循环和填充字典之外,还有其他选择吗?谢谢你的帮助。
您可以使用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()));
}
这应该为您提供所需的输出。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句