gpt4 book ai didi

c# LINQ 加入两个列表

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

我在尝试将两个列表与 LINQ 一起加入时正在战斗。

我得到了什么...

类(class)人:

class Person
{
public string Name { get; private set; }
public int Age { get; private set; }
public bool Parent { get; private set; }
public bool Child { get; private set; }
public int Housenumber { get; private set; }

public Person(string name, int age, bool parent, bool child, int housenumber)
{
Name = name;
Age = age;
Parent = parent;
Child = child;
Housenumber = housenumber;
}
}

类(class)房子:
class House
{
public int Housenumber { get; private set; }
public int Rooms { get; private set; }
public string Color { get; private set; }

public House(int housenumber, int rooms, string color)
{
Housenumber = housenumber;
Color = color;
Rooms = rooms;
}
}

人员名单:
private static List<Person> people = new List<Person>
{
new Person("Joel", 12, false, true, 1),
new Person("jana", 22, false, false, 2),
new Person("Housi", 45, true, false, 3),
new Person("Kurt", 25, false, false, 4),
new Person("Sebastian", 65, true, false, 1),
new Person("George", 14, false, true, 2),
new Person("Noel", 50, true, false, 3)
};

以及房屋 list :
private static List<House> houses = new List<House>
{
new House(1, 4, "blue"),
new House(2, 2, "red"),
new House(3, 3, "black"),
new House(4, 1, "violett")
};

我想做的是创建一个包含“House”对象的新列表。
但只有那些至少有两个人住的房子!

我被困在这里:
var houseWithMorePeople = from house in houses
join person in people
on house.Housenumber equals person.Housenumber
join person2 in people
on person.Housenumber equals person2.Housenumber
select house;

最佳答案

您可以简单地使用 WhereCount像这样:

var result = houses
.Where(h => people.Count(p => p.Housenumber == h.Housenumber) >= 2)
.ToList();

关于c# LINQ 加入两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37207817/

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