gpt4 book ai didi

c# - 透视 IEnumerable 列表

转载 作者:太空宇宙 更新时间:2023-11-03 11:25:50 30 4
gpt4 key购买 nike

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

考虑下面的类,我将把它压缩为仅相关的属性,这样你就明白了……

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 来获取初始的 Assets 列表,如下所示,这可能是开展业务的更好地方......

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();
}

任何帮助/指导将不胜感激...

提前致谢。

最佳答案

我正在使用 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()
})
})




我以为你的类(class)看起来像这样

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;}
}

关于c# - 透视 IEnumerable 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9360555/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com