在单个连接中的多个字段上进行LINQ连接,可以使用Join
方法和Lambda
表达式来实现。以下是一个示例:
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<Person> persons = new List<Person>
{
new Person { FirstName = "John", LastName = "Doe" },
new Person { FirstName = "Jane", LastName = "Doe" },
new Person { FirstName = "John", LastName = "Smith" },
new Person { FirstName = "Jane", LastName = "Smith" }
};
List<Address> addresses = new List<Address>
{
new Address { PersonName = "John Doe", Street = "123 Main St" },
new Address { PersonName = "Jane Doe", Street = "456 Elm St" },
new Address { PersonName = "John Smith", Street = "789 Oak St" },
new Address { PersonName = "Jane Smith", Street = "987 Pine St" }
};
var query = persons.Join(addresses,
person => person.FirstName + " " + person.LastName,
address => address.PersonName,
(person, address) => new
{
FirstName = person.FirstName,
LastName = person.LastName,
Street = address.Street
});
foreach (var item in query)
{
Console.WriteLine($"{item.FirstName} {item.LastName} - {item.Street}");
}
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Address
{
public string PersonName { get; set; }
public string Street { get; set; }
}
在这个示例中,我们有两个类:Person
和Address
。我们使用Join
方法将这两个类连接在一起,并使用Lambda
表达式来指定如何将Person
和Address
对象连接在一起。在这种情况下,我们将Person
对象的FirstName
和LastName
属性连接成一个字符串,并将Address
对象的PersonName
属性与之匹配。最后,我们从查询中获取结果,并将其输出到控制台。
这种方法可以帮助您在单个连接中的多个字段上进行LINQ连接。
领取专属 10元无门槛券
手把手带您无忧上云