代码之家  ›  专栏  ›  技术社区  ›  Sungguk Lim

检查两个IEnumerable之间的existence

  •  5
  • Sungguk Lim  · 技术社区  · 15 年前
    IEnumerable<String> existedThings = 
            from mdinfo in mdInfoTotal select mdinfo.ItemNo;
    
    IEnumerable<String> thingsToSave = 
            from item in lbXReadSuccess.Items.Cast<ListItem>() select item.Value;
    

    这里有两个 IEnumerable .

    我想检查一下 value in existedThings 存在于 thingsToSave .

    好的,我可以用3行代码来完成。

    bool hasItemNo;
    foreach(string itemNo in existedThings)
        hasItemNo= thingsToSave.Contains(itemNo);
    

    但是,它看起来很脏。

    我只想知道是否有更好的解决方案。

    7 回复  |  直到 15 年前
        1
  •  8
  •   VMAtm    15 年前
     int[] id1 = { 44, 26, 92, 30, 71, 38 };
     int[] id2 = { 39, 59, 83, 47, 26, 4, 30 };
    
     IEnumerable<int> both = id1.Intersect(id2);
    
     foreach (int id in both)
         Console.WriteLine(id);
    
     //Console.WriteLine((both.Count() > 0).ToString());
     Console.WriteLine(both.Any().ToString());
    

    寻找 Enumerable.Intersect Method

        2
  •  8
  •   Hans Passant    15 年前

    如果IEnumerable不是从实现ICollection的类中派生出来的,则被否决的答案会提出一种算法,该算法具有O(n^2)复杂性。例如,一个LINQ查询。然后,count()扩展方法必须迭代 全部的 要计算的元素。这不酷。您只需要检查结果是否包含 任何 元素:

     bool hasItemNo = existedThings.Intersect(thingsToSave).Any();
    

    顺序关系到btw,使您期望的具有最少项目数的枚举成为intersect()的参数。

        3
  •  4
  •   Fredrik Mörk    15 年前

    你可以使用 Intersect 要实现这一点:

    // puts all items that exists in both lists into the inBoth sequence
    IEnumerable<string> inBoth = existedThings.Intersect(thingsToSave);
    
        4
  •  4
  •   Giorgi    15 年前
    bool hasItemNo = existedThings.Intersect(thingsToSave).Count() > 0;
    

    如果需要,您甚至可以提供自己的比较器: Enumerable.Intersect

        5
  •  3
  •   Dan Puzey    15 年前

    它很脏,而且也不起作用!你的 hasItemNo 只会 true 如果 最后值 在里面 existedThings 是在 thingsToSave .

    不过,既然您将其标记为“linq”,那么我想这段代码对您来说是有用的:

    bool hasItemNo = thingsToSave.Intersect(existedThings).Count() > 0
    
        6
  •  2
  •   Darin Dimitrov    15 年前

    你可以试试 intersecting the two sequences 看看结果序列是否包含任何元素

        7
  •  2
  •   Lazarus    15 年前

    这里不完全清楚您真正想要什么,但是这里有一个建议,只检索thingstosave和existedthings中存在的字符串。

    IEnumerable<String> existedThings = 
            from mdinfo in mdInfoTotal select mdinfo.ItemNo;
    
    IEnumerable<String> thingsToSave = 
            from item in lbXReadSuccess.Items.Cast<ListItem>() 
            where existedThings.Contains(item.Value)
            select item.Value;