我有一个包含list属性的实体对象。我想将列表值扩展到右侧。作为LINQ的新手,我不知道该如何做到这一点。我可以强力键入一个对象,但是我必须在编译时知道计数/值,并且我想让它更具动态性。
我想要的输出类似于:
名称demo1的DEMO2 Demo3
人名1 TX TX
人名2 TX OK
人名3 TX TX OK
Main Class
public Main()
{
List<Event> events = new List<Event>();
events.Add(new Event()
{
EventDate = DateTime.Now,
EventLocation = new Location() { State = "TX" },
EventName = "Demo1"
});
events.Add(new Event()
{
EventDate = DateTime.Now,
EventLocation = events[0].EventLocation,
EventName = "Demo2"
});
events.Add(new Event()
{
EventDate = DateTime.Now,
EventLocation = new Location() { State = "OK" },
EventName = "Demo3"
});
List<Person> people = new List<Person>();
Person person1 = new Person();
person1.Name = "Person Name1";
person1.Events.Add(events[0]);
person1.Events.Add(events[1]);
Person person2 = new Person();
person2.Name = "Person Name2";
person2.Events.Add(events[0]);
person2.Events.Add(events[2]);
Person person3 = new Person();
person3.Name = "Person Name3";
person3.Events.Add(events[0]);
person3.Events.Add(events[1]);
person3.Events.Add(events[2]);
people.Add(person1);
people.Add(person2);
people.Add(person3);
}
public Main()
{
List<Event> events = new List<Event>();
events.Add(new Event()
{
EventDate = DateTime.Now,
EventLocation = new Location() { State = "TX" },
EventName = "Demo1"
});
events.Add(new Event()
{
EventDate = DateTime.Now,
EventLocation = events[0].EventLocation,
EventName = "Demo2"
});
events.Add(new Event()
{
EventDate = DateTime.Now,
EventLocation = new Location() { State = "OK" },
EventName = "Demo3"
});
List<Person> people = new List<Person>();
Person person1 = new Person();
person1.Name = "Person Name1";
person1.Events.Add(events[0]);
person1.Events.Add(events[1]);
Person person2 = new Person();
person2.Name = "Person Name2";
person2.Events.Add(events[0]);
person2.Events.Add(events[2]);
Person person3 = new Person();
person3.Name = "Person Name3";
person3.Events.Add(events[0]);
person3.Events.Add(events[1]);
person3.Events.Add(events[2]);
people.Add(person1);
people.Add(person2);
people.Add(person3);
}
答案 0 :(得分:0)
这取决于您是要在内存中还是在数据库中运行查询。在任何情况下,您都需要返回一个包含结果“动态”部分的列表,因为您无法动态生成匿名类型的成员(并且难以使用它们)。
在内存中(如示例所示),您可以编写以下查询:
// Find names of all events (for all people)
var allNames =
(from p in people
from e in p.Events
select e.EventName).Distinct();
// Find events for every person
var res =
from p in people
let known = p.Events.ToDictionary(e => e.EventName)
select new {
p.Name,
Events = allNames.Select(n =>
known.ContainsKey(n)?known[n].EventLocation:"N/A")
};
第一个查询获取所有事件的名称(我们稍后使用它来为每个人查找所有事件的值)。第二个查询遍历所有人。它首先创建带有事件的字典(用于在内存中快速查找),然后迭代所有事件名称并尝试在字典中找到它们(如果找不到则返回“N / A”)。