【问题标题】:How to use Except method in list in c#如何在c#的列表中使用Except方法
【发布时间】:2012-10-24 18:47:59
【问题描述】:

我创建了一个两个 int 类型的列表,并使用 except 方法将仅在 list1 中的项目分配给 list1。例如

List<int> list1 = new List<int>();
List<int> list2 = new List<int>();

list1 = {1,2,3,4,5,6} // get items from the database
list2 = {3,5,6,7,8}   // get items from the database

list1 = list1.Except(list2); // gives me an error.

请给我建议。正确的做法是什么。

【问题讨论】:

    标签: c# .net list ienumerable


    【解决方案1】:

    Except方法返回IEnumerable,需要将结果转化为列表:

    list1 = list1.Except(list2).ToList();
    

    这是一个完整的例子:

    List<String> origItems = new List<String>();
        origItems.Add("abc");
        origItems.Add("def");
        origItems.Add("ghi");
        
        List<String> newItems = new List<String>();
        newItems.Add("abc");
        newItems.Add("def");
        newItems.Add("super");
        newItems.Add("extra");
        
        List<String> itemsOnlyInNew = newItems.Except(origItems).ToList();
        foreach (String s in itemsOnlyInNew){
            Console.WriteLine(s);
        }
    

    由于 origItems 中唯一不存在的项目是 superextra,因此结果输出是:

    超级

    额外的

    【讨论】:

    猜你喜欢
    • 2023-02-26
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 2014-12-19
    相关资源
    最近更新 更多