English 中文(简体)
我如何选择 ListA 中具有与 ListB 中项目属性相符的属性的项目?
原标题:How can I select items in ListA that have a property that matches an item s property in ListB?
  • 时间:2012-05-25 18:57:13
  •  标签:
  • c#

我有一个 List<A> , 其中A 包含一个名为 TypeId 的属性, 还有一个 List<B> , 其中B 也包含一个名为 TypeId 的属性。

我想从 list<A> 中选择所有项目,因为 list<B> 中包含一个 B.TypeId = A.TypeId 的项目。

ListA.Add(new A { TypeId = 1 });
ListA.Add(new A { TypeId = 2 });
ListA.Add(new A { TypeId = 3 });

ListB.Add(new B { TypeId = 3 });
ListB.Add(new B { TypeId = 4 });
ListB.Add(new B { TypeId = 1 });

???? // Should return items 1 and 3 only

最有效的方法是什么?

我知道事情很简单 但我的大脑今天感觉很愚蠢...

最佳回答

使用 LINQ, 使用 join 方法比较简单 。

var join = ListA.Join(ListB, la => la.TypeId, lb => lb.TypeId, (la, lb) => la);
问题回答

I guess you are trying to do an intersect operation, and it should be possible with the Intersect Extension. One advantage here is that intersect will run in O(m + n). Example program :

class Program
{
    class Bar
    {
        public Bar(int x)
        {
            Foo = x;
        }
        public int Foo { get; set; }
    }

    class BarComparer : IEqualityComparer<Bar>
    {
        public bool Equals(Bar x, Bar y)
        {
            return x.Foo == y.Foo;
        }

        public int GetHashCode(Bar obj)
        {
            return obj.Foo;
        }

    }
    static void Main(string[] args)
    {
        var list1 = new List<Bar>() { new Bar(10), new Bar(20), new Bar(30)};
        var list2 = new List<Bar>() { new Bar(10),  new Bar(20) };
        var result = list1.Intersect(list2, new BarComparer());

        foreach (var item in result)
        {
            Console.WriteLine(item.Foo);
        }
    }
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签