透视IEnumerable列表

时间:2012-02-20 11:41:50

标签: c# asp.net linq-to-sql group-by ienumerable

我正在尝试将一些groupby / crosstabbing逻辑应用于用户定义对象的IEnumerable列表,并且想知道是否有人可以帮助我。我坚持使用现有的(相当恼人的)对象模型来处理,但无论如何这里...... ...

考虑以下课程,我将仅缩小到相关属性,以便获得jist ...

public class Holding
{
   private void Institution;
   private string Designation;
   private Owner Owner;
   private Event Event;
   private Shares Shares;
}

我想将此转换为满足以下内容的列表......

  • 该对象按机构分组。
  • 这个机构的父列表包含一个新对象的列表,该对象具有指定和所有者的唯一组合。
  • 现在,对于指定和所有者的这一组合,我们将获得另一个独特事件的子列表。

所以它基本上是3个列表。

我不确定这是否可以使用IEnumerable List,我已经玩了很多关于GroupBy扩展方法到目前为止无济于事。我希望大多数人这样做,但是我使用linq-to-sql获取最初的馆藏清单,如下所示,可能是开展业务的最佳地点......

public static List<Holding> GetHoldingsByEvents(
    int eventId1,
    int eventId2)
{
    DataClassesDataContext db = new DataClassesDataContext();

    var q = from h in db.Holdings
             where
               h.EventId == eventId1 ||
               h.EventId == eventId2
             select h;

    return q.Distinct().ToList();
}

非常感谢任何帮助/指导...

提前致谢。

1 个答案:

答案 0 :(得分:2)

我正在使用ToLookup方法,这是一种分组,它需要两个参数,第一个是用于定义组键的函数,下一个是用作选择器的函数(从匹配中取出的内容) )。

items.ToLookup(c=>c.Institution.InstitutionId, c => new {c.Designation, c.Owner, c.Event})
    .Select(c => new {
        // find the institution using the original Holding list
        Institution = items.First(i=>i.Institution.InstitutionId == c.Key).Institution,
        // create a new property which will hold the groupings by Designation and Onwner
        DesignationOwner = 
                // group (Designation, Owner, Event) of each Institution by Designation and Owner; Select Event as the grouping result
                c.ToLookup(_do => new {_do.Designation, _do.Owner.OwnerId}, _do => _do.Event)
                            .Select(e => new {
                                // create a new Property Designation, from e.Key
                                Designation = e.Key.Designation,
                                // find the Owner from the upper group ( you can use items as well, just be carreful this is about object and will get the first match in list)
                                Owner = c.First(o => o.Owner.OwnerId == e.Key.OwnerId).Owner,
                                // select the grouped events // want Distinct? call Distinct
                                Events = e.Select(ev=>ev)//.Distinct()
                            })
    })




我认为你的课程看起来像这些

public class Holding
{
   public Institution Institution {get; set;}
   public string Designation {get; set;}
   public Owner Owner {get; set;}
   public Event Event {get; set;}   
}
public class Owner 
{
  public int OwnerId {get; set;}
}

public class Event 
{
  public int EventId {get; set;}
}

public class Institution 
{
  public int InstitutionId {get; set;}
}