从2个现有列表创建新列表,其中存在匹配值

时间:2012-11-27 00:05:44

标签: c# list object

我有2个包含2种不同类型对象的列表。是否可以比较两个列表中的对象并创建一个包含具有匹配属性值的对象的新列表?

例如,如果我有一个总线列表(具有属性'busID')和一个驱动程序列表(也有一个属性'busID')。我可以创建一个新的列表,其中(bus.busesID = drivers.busID)?

我意识到这个问题很模糊,不包含示例代码。我虽然被困在这里。

3 个答案:

答案 0 :(得分:1)

您可以使用LINQ在此ID上加入这两个集合,例如生成一个总线元组及其驱动程序。使用LINQ语法,它看起来像这样:

var result = from bus in buses
             join driver in drivers on bus.busID equals driver.busID
             select new { Bus = bus, Driver = driver }

这可能会为您介绍几项新功能,例如 LINQ 本身或 anonymous type 定义。

结果是一个查询,它被懒惰地执行并产生一组总线+驱动器对。

答案 1 :(得分:0)

试试这个:

var query =
    from driver in drivers
    join bus in buses on driver.busID equals bus.busID
    select new { driver, bus };

var results = query.ToList();

答案 2 :(得分:0)

如果您正在使用更抽象的解决方案,那么您可以使用反射。

    class A
    {
        public int x { get; set; }
        public int y { get; set; }
    }

    class B
    {
        public int y { get; set; }
        public int z { get; set; }
    }

    static List<A> listA = new List<A>();
    static List<B> listB = new List<B>();

    static void Main(string[] args)
    {
        listA.Add(new A {x = 0, y = 1});
        listA.Add(new A {x = 0, y = 2});
        listB.Add(new B {y = 2, z = 9});
        listB.Add(new B {y = 3, z = 9});

        // get all properties from classes A & B and find ones with matching names and types
        var propsA = typeof(A).GetProperties();
        var propsB = typeof(B).GetProperties();
        var matchingProps = new List<Tuple<PropertyInfo, PropertyInfo>>();
        foreach (var pa in propsA)
        {
            foreach (var pb in propsB)
            {
                if (pa.Name == pb.Name && pa.GetType() == pb.GetType())
                {
                    matchingProps.Add(new Tuple<PropertyInfo, PropertyInfo>(pa, pb));
                }
            }
        }

        // foreach matching property, get the value from each element in list A and try to find matching one from list B
        var matchingAB = new List<Tuple<A, B>>();
        foreach (var mp in matchingProps)
        {
            foreach (var a in listA)
            {
                var valA = mp.Item1.GetValue(a, null);

                foreach (var b in listB)
                {
                    var valB = mp.Item2.GetValue(b, null);

                    if (valA.Equals(valB))
                    {
                        matchingAB.Add(new Tuple<A, B>(a, b));
                    }
                }
            }
        }

        Console.WriteLine(matchingAB.Count); // this prints 1 in this case
    }

Sidenote:Tuple是一个.NET 4类,如果你不能使用它,那么你可以轻松编写自己的:Equivalent of Tuple (.NET 4) for .NET Framework 3.5