【问题标题】:I tried to do a "Except()" but it did not work [duplicate]我试图做一个“Except()”但它没有工作[重复]
【发布时间】:2012-11-13 14:02:10
【问题描述】:

可能重复:
how can I do use Except() between two SelectListItem lists

我有两个IEnumerable <SelectListItem> 类型的列表,我需要创建一个新的IEnumerable <SelectListItem>,其中包含第二个列表中不存在的第一个列表的元素。 我该怎么做?

我尝试使用 Except() 进行操作,但没有成功

示例代码:

IEnumerable<SelectListItem> SelectListItemA = ....;
IEnumerable<SelectListItem> SelectListItemB = ....;
IEnumerable<SelectListItem> Except = SelectListItemA.Except(SelectListItemB);

【问题讨论】:

  • “它没有用”是什么意思?
  • @L.B:他也问过这个问题:p
  • 真的,不要再问同样的问题了,而且肯定不是第一次半小时!

标签: c# except selectlistitem


【解决方案1】:

这应该可以了,看看this example

            double[] numbers1 = { 2.0, 2.1, 2.2, 2.3, 2.4, 2.5 };
            double[] numbers2 = { 2.2 };

            IEnumerable<double> onlyInFirstSet = numbers1.Except(numbers2);

            foreach (double number in onlyInFirstSet)
                Console.WriteLine(number);

            /*
             This code produces the following output:

             2
             2.1
             2.3
             2.4
             2.5
            */

我想问题是你的情况下的平等比较器(对于 SelectedListItem)没有定义,或者更好地说看起来相同的东西不仅仅是相同的对象,在这种情况下你必须提供 [IEqualityComparer]定义哪些元素实际上是相等的1:

public static IEnumerable<TSource> Except<TSource>(
    this IEnumerable<TSource> first,
    IEnumerable<TSource> second,
    IEqualityComparer<TSource> comparer
)

【讨论】:

    猜你喜欢
    • 2022-11-06
    • 2022-12-06
    • 1970-01-01
    • 2019-03-30
    • 2019-03-05
    • 2021-04-22
    • 2022-01-09
    • 1970-01-01
    • 2022-06-15
    相关资源
    最近更新 更多