我有两个通用类型列表 A
和 B
:
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
的实例包含来 self 的数据库的值。
例如:
A[0] = {1, "11", true}, A[1] = {2, "22", true}, A[2] = {3, "33", false}
和
B = {2, 3}
期望的结果由A[1]
和A[2]
组成。
最佳答案
听起来你的意思是“通过检查第二个列表的属性来过滤第一个列表中的项目”——在这种情况下,我建议:
从第二个列表构建索引:
// 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));
这将非常有效地为您提供一个仅包含 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
关于c# - 如何将两个不同的列表映射到一个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38123540/