C# Linq-将不同对象的子列表合并到单个对象中
我有一个对象,它有一个日期和一组人,一个人有名字和姓氏。比如:C# Linq-将不同对象的子列表合并到单个对象中,c#,linq,C#,Linq,我有一个对象,它有一个日期和一组人,一个人有名字和姓氏。比如: PeopleInfo ---------- DateTime - StartDate List<Person> - People Person ------ string - FirstName string - LastName 预期产量 在林克这可能吗 谢谢您可以: List<PeopleInfo> peopleInfos = ... var merged = from peopleInfo in
PeopleInfo
----------
DateTime - StartDate
List<Person> - People
Person
------
string - FirstName
string - LastName
预期产量
在林克这可能吗
谢谢您可以:
List<PeopleInfo> peopleInfos = ...
var merged = from peopleInfo in peopleInfos
group peopleInfo by peopleInfo.StartDate into dateGroup
select new PeopleInfo
{
StartDate = dateGroup.Key,
People = dateGroup.SelectMany(pi => pi.People)
.Distinct()
.ToList()
};
List peopleInfos=。。。
var merged=来自peopleInfos中的peopleInfo
按peopleInfo.StartDate将peopleInfo分组为dateGroup
选择new PeopleInfo
{
StartDate=dateGroup.Key,
People=dateGroup.SelectMany(pi=>pi.People)
.Distinct()
托利斯先生()
};
但这看起来真的像一个黑客;我建议您在设计容器类时,首先要防止这种“重复日期”的情况发生。e、 g.ILookup
或IDictionary
或HashSet
的一种实现,它使用StartDate
表示相等。ILookup查找=
ILookup<DateTime, Person> lookup =
(
from pi in PeopleInfos
from person in pi.People
select new {StartDate = pi.StartDate, Person = person }
).ToLookup(x => x.StartDate, x => x.Person);
(
来自PeopleInfos中的pi
来自pi中的person。People
选择新{StartDate=pi.StartDate,Person=Person}
).ToLookup(x=>x.StartDate,x=>x.Person);
或
列表=
(
来自PeopleInfos中的pi
来自pi中的person。People
根据pi.StartDate将人员分组为g
选择new PeopleInfo(){StartDate=g.Key,People=g.ToList()}
)托利斯先生()
谢谢,效果很好。一个更好的实现是一个好主意,但我现在所做的只是暂时的尝试。我同意OP模型还有一些不尽如人意的地方,但是你的解决方案是正确的+1.我要警告的是,虽然这是正确的,但它不必要地展平了整个输入集合,并从头开始分组。不必要的展平?要多少钱?
List<PeopleInfo> peopleInfos = ...
var merged = from peopleInfo in peopleInfos
group peopleInfo by peopleInfo.StartDate into dateGroup
select new PeopleInfo
{
StartDate = dateGroup.Key,
People = dateGroup.SelectMany(pi => pi.People)
.Distinct()
.ToList()
};
ILookup<DateTime, Person> lookup =
(
from pi in PeopleInfos
from person in pi.People
select new {StartDate = pi.StartDate, Person = person }
).ToLookup(x => x.StartDate, x => x.Person);
List<PeopleInfo> list =
(
from pi in PeopleInfos
from person in pi.People
group person by pi.StartDate into g
select new PeopleInfo() { StartDate = g.Key, People = g.ToList() }
).ToList()