【问题标题】:How can I get data from a list with a where clause to another list?如何从带有 where 子句的列表中获取数据到另一个列表?
【发布时间】:2010-10-04 01:55:29
【问题描述】:

我有一个包含多个类的列表,其中包含一个整数 (Id) 属性。

我也有一个整数列表。

现在,我想将我的对象列表修剪为仅具有整数列表中的属性的那些类。

例子:

List of MyObject
[MyObjectA].Id = 1
[MyObjectB].Id = 2
[MyObjectC].Id = 3
[MyObjectD].Id = 4

List of Integer
1
2

Final list should be 
[MyObjectA]
[MyObjectB]

我该怎么做?

【问题讨论】:

    标签: c# linq .net-3.5 c#-3.0


    【解决方案1】:

    你可以使用包含:

    var finalList = originalList.Where(x => idList.Contains(x.Id)).ToList();
    

    或加入:

    var finalList = (from entry in originalList
                    join id in idList on entry.Id equals id
                    select entry).ToList();
    

    【讨论】:

    • 您的意思是 entry.Id 而不是 x.Id? (在使用连接的情况下)
    • 我最喜欢解决方案 1。连接很好,但我更喜欢第一个的可读性。
    • @shahkalpesh:已修复,谢谢。 @Longhorn213:如果 idList 最终变得非常大,第二个会明显更快。它基本上构建了一个哈希映射,而不是对每个条目进行线性扫描。
    【解决方案2】:

    怎么样:

    list.RemoveAll(x => list2.IndexOf(x.Id) >= 0);
    

    【讨论】:

      【解决方案3】:

      应该这样做:

      // Assume objList is IEnumerable<MyObject> and intList is IEnumerable<int>.
      IEnumerable<MyObject> intersection =
        from obj in objList
          join i in intList on obj.Id equals i
        select obj
      

      请注意,如果多个对象具有相同的 id,或者该 id 在列表中多次列出并且一个对象与之对应,则该对象将在结果列表中出现多次。

      我认为该组更适合较大的列表,因为其他一些解决方案会多次遍历列表以搜索相应的对象。

      【讨论】:

        【解决方案4】:

        或者,如果您有两个列表,每个列表都有属性,试试这个:

        List<someObj1> firstList ... //assume this has items
        List<otherObj2> secondList ... //assume this has items
        var finalList = firstList.Where(so1 => secondList.Select(oo2 => oo2.Prop1).Contains(so1.Prop1) && so1.Prop2 == "foo");
        
        //Prop1 is a property of the someObj1 and otherObj objects. 
        //Prop2 is a property of the someObj1 object.
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-03-01
          • 2021-08-17
          • 1970-01-01
          • 1970-01-01
          • 2015-12-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多