c# - 如何将两个不同的列表映射到一个列表?

标签 c# asp.net linq

我有两个通用类型列表 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 的实例包含来 self 的数据库的值。

例如:

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

关于c# - 如何将两个不同的列表映射到一个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38123540/

相关文章:

c# - 使用 xmldocument 中的 xpath 选择注释之间的节点

javascript - 空字符 ('\0' ) 导致 updatepanel 出现问题

c# - 我可以在 MVC 站点下的虚拟目录中拥有传统的 ASP.NET Web 应用程序吗?

asp.net - session 在一个站点上有效,但在同一台计算机上的另一个站点上无效

c# - LINQ to XML 和 LINQ to Objects 语法

c# - 从数据库中获取字段值的动态 LINQ 查询

c# - 如何在 Visual Studio 中调试类库

c# - Getter 无体,Setter 有

c# - 在 XAML ProgressBar 的 ValueChanged 事件上绑定(bind)平滑动画

c# - 顺序列表与另一个列表的顺序相同