gpt4 book ai didi

c# - 连接两个 List,其中每个列表中的字段值相等

转载 作者:太空宇宙 更新时间:2023-11-03 19:10:11 25 4
gpt4 key购买 nike

class Person
{
public String FirstName { get; set; }
public String LastName { get; set; }

public Person(String firstName String lastName)
{
FirstName = firstName
LastName = lastName;
}
}

public static void Main()
{
List<Person> males = new List<Person>();

males.Add(new Person() {FirstName = "Fred", LastName = "Blogs"});
males.Add(new Person() {FirstName = "John", LastName = "James"});
males.Add(new Person() {FirstName = "Harry", LastName = "Adams"});
males.Add(new Person() {FirstName = "Peter", LastName = "Blogs"});

List<Person> females = new List<Person>();

females.Add(new Person() {FirstName = "Mary", LastName = "Blogs"});
females.Add(new Person() {FirstName = "Anne", LastName = "James"});
females.Add(new Person() {FirstName = "Jane", LastName = "Doe"});

List<Person> results = new List<Person>();

results = males.Concat(females)...; // This is where I stumble ??
}

List<Person> results需要包含 males.LastName 所在的所有行和 females.LastName存在于两个列表中。

List<Person> results应该包含...

    FirstName = "Fred", LastName = "Blogs"});
FirstName = "John", LastName = "James"});
FirstName = "Peter", LastName = "Blogs"});
FirstName = "Mary", LastName = "Blogs"});
FirstName = "Anne", LastName = "James"});

注意:Harry AdamsJane Doe 应该被排除在外,因为他们的姓氏不在两个列表中。

(换句话说,如果我最喜欢的啤酒公司统治世界,我需要这样的东西:

`results = males.Concat(female).Where(males.LastName == female.LastName);`

它会弄清楚...啊!如果只是)

如有任何帮助,我们将不胜感激。

最佳答案

var result = males.Concat(females).Where(p => males.Any(x => p.LastName == x.LastName) && 
females.Any(x => p.LastName == x.LastName))
.ToList();

这是给出预期结果的完整代码:

[Test]
public void LINQTest()
{
List<Person> males = new List<Person>();

males.Add(new Person() { FirstName = "Fred", LastName = "Blogs" });
males.Add(new Person() { FirstName = "John", LastName = "James" });
males.Add(new Person() { FirstName = "Harry", LastName = "Adams" });
males.Add(new Person() { FirstName = "Peter", LastName = "Blogs" });

List<Person> females = new List<Person>();

females.Add(new Person() { FirstName = "Mary", LastName = "Blogs" });
females.Add(new Person() { FirstName = "Anne", LastName = "James" });
females.Add(new Person() { FirstName = "Jane", LastName = "Doe" });

List<Person> results = new List<Person>();

var result = males.Concat(females).Where(p => males.Any(x => p.LastName == x.LastName) &&
females.Any(x => p.LastName == x.LastName))
.ToList();

Assert.AreEqual(result.Count, 5); // true
}

或者你可以像这样使用 Intersect 和 Contains,它可能会快得多。

 var names = males.Select(p => p.LastName)
.Intersect(females.Select(p => p.LastName))
.ToList();
var result = males.Concat(females)
.Where(p =>names.Contains(p.LastName))
.ToList();

关于c# - 连接两个 List<T>,其中每个列表中的字段值相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21366152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com