如何在ListA中选择具有与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

最有效的方法是什么?

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

2 个答案:

答案 0 :(得分:4)

使用LINQ,使用Join方法相当简单。

var join = ListA.Join(ListB, la => la.TypeId, lb => lb.TypeId, (la, lb) => la);

答案 1 :(得分:0)

我猜你正在尝试进行交叉操作,并且应该可以使用Intersect扩展。这里的一个优点是交叉将以O(m + n)运行。 示例程序:

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);
        }
    }
}
相关问题