如何将两个不同的列表映射到一个列表

本文关键字:列表 映射 一个 两个 | 更新日期: 2023-09-27 17:53:37

我有两个通用类型AB的列表:

public class A {
    int type;
    string params;
    bool isActive;
}
public class B {
    int type;
}

我怎么能把它们映射到一个类型A的列表,其中B.type == A.type(不是A.type == B.type !!)使用linq?

B类的实例包含可以删除或添加的int值,而A类的实例包含来自my db的值。

例如:

A[0] = {1, "11", true}, A[1] = {2, "22", true}, A[2] = {3, "33", false}

B = {2, 3}

期望结果由A[1]A[2]组成。

如何将两个不同的列表映射到一个列表

听起来您的意思是"通过检查第二个列表的属性来过滤第一个列表中的项目"—在这种情况下,我建议:

  1. 从第二个列表建立索引:

    // create an index of the "type"s to look for
    var index = new HashSet<int>(bList.Select(x => x.type));
    
  2. 使用这个来过滤数据

    // filter the primary list to values from the index
    var matches = aList.FindAll(x => index.Contains(x.type));
    

这将非常有效地为您提供A数据列表,这些数据在bList中具有相应的值。

这里是可运行的:

using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
    public class A
    {
        public int type;
        public string @params;
        public bool isActive;
    }
    public class B
    {
        public int type;
    }
    static void Main()
    {
        var aList = new List<A>
        {
            new A { type = 1, @params = "11", isActive = true },
            new A { type = 2, @params = "22", isActive = true },
            new A { type = 3, @params = "33", isActive = false },
        };
        var bList = new List<B>
        {
            new B { type = 2 },
            new B { type = 3 },
        };
        // create an index of the "type"s to look for
        var index = new HashSet<int>(bList.Select(x => x.type));
        // filter the primary list to values from the index
        var matches = aList.FindAll(x => index.Contains(x.type));
        foreach (var match in matches)
        {
            Console.WriteLine($"{match.type}, {match.@params}, {match.isActive}");
        }
    }
}
与输出:

2, 22, True
3, 33, False

您想要加入两个列表,所以找到两个列表中的所有A ?

var query = from a in aList
            join b in bList
            on a.type equals b.type
            select a;
List<A> resultList = query.ToList();

这是你要找的吗?

var result = arrayA.Where(a => arrayB.Select(b => b.type).Contains(a.type)).ToArray();

如果你有两个序列,其中两个序列都有一个应该匹配的值,并且你想从第一个序列中获取零个或多个属性,从第二个序列中获取零个或多个属性,你可以使用Enumerable.Join.

语法似乎有点难,但如果经常使用,你会习惯的。

假设在你的例子中你有一个a对象序列和一个B对象序列:

IEnumerable<A> myAobjects = ...
IEnumerable<B> myBobjects = ...
// do the join:
myAObjects.Join(myBobjects,  // join the two sequences
myAobject => myAobject.type, // from the A sequence take property type
myBobject => myBobject.type, // from the B sequence also take property type
(myAobject, myBobject) =>    // whenever the values of these properties equal, take:
 ...);

点将与您想要的myAobject和myBobject的组合进行组合,它们具有相同的属性类型值。你的问题很简单:每当myAobject。type匹配myBobject。类型,你想要完整的myAObject。在这种情况下,连接的最后一部分是:

(myAobject, myBobject) => myAobject

如果您想要返回其他内容,您可以使用如下命令:

(myAobject, myBobject) => new
{
    MyParams = myAobject.Params,
    MyOtherValue = myBObject.type,
}