【问题标题】:LINQ - Determine if ListA contains every element from ListBLINQ - 确定列表是否包含列表中的每个元素
【发布时间】:2014-08-27 04:18:15
【问题描述】:

我需要将两个列表与 LINQ 包括 重复项进行比较。 似乎有很多类似的问题,但是,我一直在搜索,并且只找到了忽略重复项的方法 - 仅检查列表 A 是否包含列表 B 中的项目,使用除外或相交。我使用 OrderBy 和 SequenceEquals 取得了一些成功,但它只有在列表大小相同时才有效。

List<Animal> ListA;
List<Animal> ListB;

// This works..
ListA = { Dog, Dog, Dog, Cat, Mouse }
ListB = { Dog, Dog, Dog, Cat, Mouse }

// However, this does not..
ListA = { Dog, Dog, Dog, Cat, Mouse, Mouse }
ListB = { Dog, Dog, Dog, Cat, Mouse }   

var result = ListA.OrderBy(animal => animal)
                  .SequenceEqual(ListB.OrderBy(animal => animal));

无论列表 A 的大小如何,我都需要它来工作。

我希望我已经设法解释了这种情况。 在实际实现中,我根据类似于 ListB 的列表列表检查 ListA,并创建一个新的“可能组合”列表。

感谢您的宝贵时间。

【问题讨论】:

  • 订单重要吗?如果顺序不重要,请在{element, count} 列表上进行正常区分,而不仅仅是元素列表。

标签: c# linq duplicates


【解决方案1】:

您必须计算出现次数。

static bool IsSubsetWithDuplicates<T>(IEnumerable<T> superset, IEnumerable<T> subset)
{
    var supersetLookup = superset.ToLookup(a => a);
    foreach (var subsetGroup in subset.ToLookup(a => a))
    {
        if(subsetGroup.Count() > supersetLookup[subsetGroup.Key].Count())
        {
            return false;
        }
    }

    return true;
}

调用代码:

var result1 = IsSubsetWithDuplicates(ListA, ListB);
var result2 = IsSubsetWithDuplicates(ListA1, ListB1);
var result3 = IsSubsetWithDuplicates(ListB1, ListA1);

【讨论】:

  • 我不知道 ToLookup。这很有意义,并且完全符合我的需要。我能够合并它并且它工作得很好。谢谢你的时间:)
【解决方案2】:

你可以像这样使用扩展方法

public static IEnumerable<T> IntersectDuplicates<T>(this IEnumerable<T> source, IEnumerable<T> target)
{
 List<T> list = target.ToList();
 foreach (T item in source)
 {
  if (list.Contains(item))
  {
   list.Remove(item);
   yield return item;
  }
 }
}

提供here

【讨论】:

    猜你喜欢
    • 2020-02-07
    • 2021-12-19
    • 2010-12-13
    • 2022-01-16
    • 1970-01-01
    • 2015-02-08
    • 2022-09-23
    • 2012-08-01
    • 1970-01-01
    相关资源
    最近更新 更多