开发者

Linq "reporting" question with list properties

I have an entity object that contains a list property. I'd like to expand the list values to the right. Being new to LINQ, I'm not sure how to do this. I could strongly type an object, but then I'd have to know the count/values at compile time and I'd like to make it more dynamic.

The output that I'm wanting is something like:


Name                  Demo1    Demo2   Demo3

Person Name1     TX          TX

Person Name2     TX                        OK

Person Name3     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,
       开发者_C百科 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);
}


It depends on whether you want to run the query in memory or in databse. In any case, you'll need to return a list with the "dynamic" part of the results, because you cannot dynamically generate members of anonymous types (and working with them would be difficult).

In memory (as in your example), you can write the following query:

// 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")
  };

The first query gets names of all events (we use it later to find a value for all event for every person). The second query iterates over all people. It first creates dictionary with events (for fast lookup in memory) and then iterates over all event names and tries to find them in the dictionary (returning "N/A" if it is not found).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜