【问题标题】:how do I get a subset of strings from list 1 which are not present in list2?如何从列表 1 中获取列表 2 中不存在的字符串子集?
【发布时间】:2011-03-09 07:23:06
【问题描述】:

我有两个列表

list 1 = { "fred", "fox", "jumps", "rabbit"};
list2 ={"fred", "jumps"}

现在我需要得到一个 list3,其中包含 list1 中不存在于 list2 中的元素。 所以清单3应该是

list3  = {"fox", "rabbit"};

我可以通过使用循环手动执行此操作,但我想知道是否有类似 list3 = list1 - list2 或其他比使用循环更好的方法。

谢谢

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    如果您使用的是 .NET 3.5 或更高版本,则可以使用Enumerable.Except

    var result = list1.Except(list2);
    

    如果你想要它作为一个列表:

    List<string> list3 = list1.Except(list2).ToList();
    

    对于旧版本的 .NET,您可以将 list1 中的字符串作为键插入字典中,然后从 list2 中删除字符串,然后字典中留下的键就是结果。

    Dictionary<string, object> d = new Dictionary<string, object>();
    foreach (string x in list1)
        d[x] = null;
    foreach (string x in list2)
        d.Remove(x);
    List<string> list3 = new List<string>(d.Keys);
    

    【讨论】:

    • @VNarasimhaM - 您需要拥有using System.Linq; 才能访问此方法。
    【解决方案2】:
    list1.Except(list2);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-05
      • 2019-05-25
      • 2012-01-12
      • 2019-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      相关资源
      最近更新 更多