透视IEnumerable列表

本文关键字:列表 IEnumerable 透视 | 更新日期: 2023-09-27 18:25:06

我正在尝试将一点groupby/crostabbing逻辑应用于用户定义对象的IEnumerable列表,不知道是否有人能帮我。我一直在使用一个现有的(相当烦人的)对象模型,但无论如何。。。

考虑下面的类,我将把它浓缩为仅相关的属性,这样你就得到了jist。。。

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

我想把它转换成一个满足以下条件的列表。。。

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

所以它基本上有三个列表。

我不确定IEnumerable List是否可能做到这一点,我在GroupBy扩展方法上玩了很多,但到目前为止都没有用。我最想这样做,但我使用linq到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();
}

如有任何帮助/指导,我们将不胜感激。。。

提前谢谢。

透视IEnumerable列表

我使用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;}
}