【问题标题】:Group by list of objects as dictionary of int, List of bjects [duplicate]按对象列表分组为int字典,对象列表[重复]
【发布时间】:2019-07-15 19:11:34
【问题描述】:

我有一个返回 N 行的存储过程。

为了简单起见,我的后端是这个 POCO,它将映射:

public class Car
{
  public int Id { get; set; }
  public string Brand { get; set; }
  public int OwnerId{ get; set;}
}

同时我还有以下POCO:

public class Owner
{
  public int Id { get; set; }
  public string FirstName { get; set; }
}

现在我想要实现的是以下,有列表:

List<Car> lstCar = db.sp.AllMyCars()
    .Select(car => new Car()
     {
        Id = car.Id,
        Brand = car.Brand,
        OwnerId = car.OwnerId
     }).ToList();

现在我想保存在 Dictionary&lt;int,List&lt;Owner&gt;&gt; 类型的字典中

编辑:

澄清一下,您已经有一个 List&lt;Car&gt;lstCar 的汽车列表,现在您想按 Id 和一个车主列表对它们进行分组,我们需要为每个车主创建一个车主列表我们需要添加汽车列表的元素并将此列表填充为汽车(您只需填写 id,没关系,没关系)。

例子:

您的字典中的 int 将是“数字”,您将在列表中填写的唯一字段是 OwnerId。

因此,您需要按编号对所有者对象列表进行分组,在这种情况下,例如编号 44 将返回 5 个所有者对象,其 ID 分别为 2、3、4、5 和 6。

【问题讨论】:

  • Dictionary&lt;List&lt;Owner&gt;,int&gt; - 你能澄清一下你想用它实现什么并展示一个字典的例子吗?
  • "在这种情况下,例如数字 44 将返回 5 个所有者对象,其 ID 为 2、3、4、5 和 6" - 描述 Dictionary&lt;int, List&lt;Owner&gt;&gt; - 你能重新阅读你的问题吗并确保它是一致的?
  • 这就是我想要的 Alexei 对不起,我会编辑它。

标签: c# linq


【解决方案1】:

来自Dictionary&lt;TKey, TValue&gt; 的定义,其中 TKey 是键,TValue 是值对象。因此Dictionary&lt;List&lt;Owner&gt;, int&gt; grouped 需要是Dictionary&lt;int, List&lt;Owner&gt;&gt; grouped

另一方面,我相信你正在寻找Dictionary&lt;int, Owner&gt; grouped

 Dictionary<int, Owner> grouped = 
    myList.Items
        .GroupBy(elem => elem.Id)
        .ToDictionary(com => com.Key, com => new Owner() 
          { 
            Id = elem.Id, 
            Firstname = elem.Firstname 
          });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-11
    • 2018-05-24
    • 2021-06-28
    • 2010-11-15
    • 2018-08-01
    • 2015-12-15
    • 2021-06-24
    相关资源
    最近更新 更多