【问题标题】:Group collections on the basis of Id using linq使用 linq 根据 Id 对集合进行分组
【发布时间】:2015-06-02 13:41:59
【问题描述】:

我有三个不同的集合,分别命名为 Collection1、Collection2、Collection3。现在我想按他们的 ID 对它们进行分组,还想根据他们的最大数量来订购该 ID。我想要的第三件事是将该值添加到 Icollection 。 我的收藏如下:

Collection1:
   value1
   Id1
   value2 
   ...

Collection2:
   value1
   Id1
   value2 
   Id2
   ...

Collection3:
   value1
   Id1
   value2 
   Id2
   ... 

注意:ID 在集合中是唯一的。 collection1 或 collection2 或 collection3 的 Id1 可以相同,但集合内的 Id 不能相同。 我所做的如下:

var query = Collection1.Concat.Select(a => a.CountryId).Concat(Collection2.Select(b => b.CountryId).Concat(Collection3.Select(c => c.CountryId).GroupBy(x => x).OrderByDescending(x => x.Count()).ToDictionary(x => x.Key, x => x.Count());

为了将该值分配给 ICollection 变量,这就是我所做的:

 foreach (var item in query )
 {
   ICollect.Add(item.Key);
 } 

我不确定使用.ToDictionary。任何人都可以为此提出不同的方法。 谢谢。

【问题讨论】:

    标签: c# linq lambda


    【解决方案1】:

    所以您想按 ID 合并所有集合和分组?由于 ID 在每个集合中都是唯一的,因此 group-size 最多可以有 3 个。

    var allIDs = Collection1.Select(x => x.ID)
        .Concat(Collection2.Select(x => x.ID))
        .Concat(Collection3.Select(x => x.ID))
        .GroupBy(id => id)
        .OrderByDescending(g => g.Count())
        .Select(g => g.Key);
    
    foreach(var id in allIDs)
        otherCollection.Add(id);
    

    如果您想保留每个 ID 的计数,可以使用 ToLookup

    var idLookup = Collection1.Select(x => x.ID)
        .Concat(Collection2.Select(x => x.ID))
        .Concat(Collection3.Select(x => x.ID))
        .ToLookup(id => id)
        .OrderByDescending(g => g.Count());
    foreach(var g in idLookup)
    {
        otherCollection.Add(g.Key);
        // you get the count in this way:
        int count = g.Count();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-27
      • 1970-01-01
      相关资源
      最近更新 更多