【问题标题】:I want to search a List of string items with another List. Is it possible?我想用另一个列表搜索字符串项目列表。可能吗?
【发布时间】:2020-11-27 09:25:45
【问题描述】:

商店

  1. 在一个列表中找到项目。

  2. 在另一个列表中未找到项目。 我通过这样做得到了第一部分

       for(int i = 0; i < list1.Count; i++)
        {
            for (int j = 0; j < list2.Count; j++)
            {
                if (list1[i] == list2[j]))
                {
                    list3.Add(list1[i]);
                    continue;
                }
             }
         }
    

我需要“第二部分”。还有更好的方法来搜索列表,但我更喜欢这个。

【问题讨论】:

  • 这能回答你的问题吗? Get the difference between two lists using LINQ
  • @MathewHD 我认为他的问题是获取列表中不存在的项目
  • 顺便说一句...您可以在“找到”列表的解决方案中删除 continue 语句。在它所在的地方,它对你没有任何作用,因为在 list3.Add() 调用之后,它无论如何都会在内部 for 循环中“继续”。

标签: c# list search


【解决方案1】:

你可以试试

var list3 = list1.Where(x => list2.Any(y => x == y));
var list4 = list1.Except(list3);

上面的代码会给你 IEnumerable 如果你想要一个 List 只需在分号前添加 .Tolist()(;)

如果您需要 list4 以及 list1 和 list2 中不常见的项目,那么

var list3 = list1.Where(x => list2.Any(y => x == y));
var list4 = list1.Except(list3).Concat(list2.Except(list3));

更多阅读脚注:

Enumerable.ToList

Enumerable.Except

【讨论】:

    【解决方案2】:

    您可以为此使用 Linq 的 Intersect()Except()

    var data    = new List<string>{"A", "B", "C", "D", "E", "F", "G", "H", "I"};
    var targets = new List<string>{"C", "D", "E", "F"};
    
    var found    = data.Intersect(targets).ToList();
    var notFound = data.Except   (targets).ToList();
    
    Console.WriteLine("Found:     " + string.Join(", ", found));
    Console.WriteLine("Not found: " + string.Join(", ", notFound));
    

    【讨论】:

    【解决方案3】:

    当我认为您正在学习和/或研究循环时,我看到其他答案使用 LINQ(这是迄今为止最好的方法)。因此,如果您更愿意像处理“找到”列表一样遵循“基本”方法,您可以尝试以下方法来处理“未找到”列表:

    for (int i = 0; i < list1.Count; i++)
    {
        bool add = true;
        for (int j = 0; j < list2.Count; j++)
        {
            if (list1[i] == list2[j])
            {
                add = false;
                break;
            }
        }
        if (add == true)
        {
            list4.Add(list1[i]);
        }
    }
    

    如果您的目的不仅仅是像我假设的那样学习语言和语法,请使用其他使用 LINQ 的答案,因为它们更专业。

    【讨论】:

    • 而不是bool值可以简化为if (list1[i] == list2[j])) list3.Add(list1[i]); else list4.Add(list1[i]);
    • @Lucifer 那行不通。每次 list1 中的元素与 list2 中的元素不匹配时,您都会将该 list1 元素添加到 list4 中。您最终会将 list1 的所有元素放入 list4 中。实际上,更糟糕的是,因为其中许多会重复多次。
    猜你喜欢
    • 1970-01-01
    • 2015-10-10
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 2022-01-21
    • 1970-01-01
    相关资源
    最近更新 更多