c# - Linq:从两个不同的列表中找到相似的对象

标签 c# linq

我有两个单独的自定义对象列表。在这两个单独的列表中,可能有一些对象在两个列表之间是相同的,除了一个字段(“id”)。我想知道一种查询这两个列表以找到重叠的聪明方法。我附上了一些代码来帮助澄清。如有任何建议,我们将不胜感激。

namespace ConsoleApplication1
{
class userObj
{
    public int id;
    public DateTime BirthDate;
    public string FirstName;
    public string LastName;
}

class Program
{
    static void Main(string[] args)
    {
        List<userObj> list1 = new List<userObj>();
        list1.Add(new userObj()
        {
            BirthDate=DateTime.Parse("1/1/2000"),
            FirstName="John",
            LastName="Smith",
            id=0
        });
        list1.Add(new userObj()
        {
            BirthDate = DateTime.Parse("2/2/2000"),
            FirstName = "Jane",
            LastName = "Doe",
            id = 1
        });
        list1.Add(new userObj()
        {
            BirthDate = DateTime.Parse("3/3/2000"),
            FirstName = "Sam",
            LastName = "Smith",
            id = 2
        });



        List<userObj> list2 = new List<userObj>();
        list2.Add(new userObj()
        {
            BirthDate =  DateTime.Parse("1/1/2000"),
            FirstName = "John",
            LastName = "Smith",
            id = 3
        });
        list2.Add(new userObj()
        {
            BirthDate = DateTime.Parse("2/2/2000"),
            FirstName = "Jane",
            LastName = "Doe",
            id = 4
        });


        List<int> similarObjectsFromTwoLists = null;
        //Would like this equal to the overlap. It could be the IDs on either side that have a "buddy" on the other side: (3,4) or (0,1) in the above case.

    }
}
}

最佳答案

我不知道你为什么要 List<int> ,我想这就是你想要的:

var intersectingUser = from l1 in list1
                       join l2 in list2
                       on new     { l1.FirstName, l1.LastName, l1.BirthDate }
                       equals new { l2.FirstName, l2.LastName, l2.BirthDate }
                       select new { ID1 = l1.id, ID2 = l2.id };
foreach (var bothIDs in intersectingUser)
{
    Console.WriteLine("ID in List1: {0} ID in List2: {1}", 
                     bothIDs.ID1, bothIDs.ID2);
}

输出:

ID in List1: 0 ID in List2: 3
ID in List1: 1 ID in List2: 4

关于c# - Linq:从两个不同的列表中找到相似的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25850349/

相关文章:

c# - 使用带有 Entity Framework 的动态字段按子记录排序

c# - 使用字典键过滤列表

c# - .Net 3.5 中的 Configuration.Save() 在部署/ Release模式下不起作用

c# - 为什么 win32 上没有 c# native 编译器项目?

c# - ListBlobsSegmentedAsync 不返回所有 blob 目录

c# - 如何在 LINQ 中比较日期(Likewise Like 在 SQL 查询中)

.net - 通过 LINQ 查询绑定(bind)到 GridView 无法访问部分类属性

c# - MS CRM 插件。 C#如何保证关键 block 的单次执行?

C# - 转换为基本类型如何工作?

c# - MySql 中 EF5 的最小可用整数