【问题标题】:How to convert an anonymously typed List to List<T>?如何将匿名类型的 List 转换为 List<T>?
【发布时间】:2010-02-09 12:56:13
【问题描述】:

这个简单的 Linq 查询:

from c in mycontext.Customers
join o in mycontext.Orders on c.CustomerId equals o.CustomerId
where o.Status == 1
select new {c, o}

会导致

List<{c:Customer, o:Order}>

拨打ToList()之后。

将这个匿名输入的列表转换为客户列表 (List&lt;Customer&gt;) 的最简单方法是什么?

编辑:我需要额外条件的订单,我已经改变了我原来的问题。

【问题讨论】:

  • 您是否需要订单?如果不是,您可以只“选择 c”而不是“选择新 {c,o}”
  • 如果您只需要客户,为什么还要加入订单?

标签: c# .net linq generics anonymous-types


【解决方案1】:
result.Select(o => o.Customer).ToList();

这是你的意思吗?

【讨论】:

  • 这将返回每个客户X 次,其中X 是与每个客户关联的订单数。你的回答没有错,但也许他想要不同的客户,他最好知道这个例子没有做到这一点。
  • 好点。问题是为什么要加入 Orders?无论如何,如果需要,您仍然可以调用 .Distinct() ...
  • 这不是最简单的方法
【解决方案2】:

非常基本的方法,正如您明确询问“转换 this 匿名输入 [...] 的最简单方法是什么”:

var anonymousEnumerable = from c in mycontext.Customers
                          join o in mycontext.Orders on c.CustomerId equals o.CustomerId
                          select new
                          {
                              c,
                              o
                          };
var typedEnumerable = anonymousList.Select(item => item.c).Distinct(); // either referenceCheck or you supply an IEqualityComparer<Customer>-implementation

也许您可以向我们提供更多信息以及您想要实现的目标!

【讨论】:

  • 我想尽可能简单地将我的 Linq 查询结果转换为 List
  • 对于 this 列表,我给了你答案......如果你想要一个更通用(又名通用)的答案,可能还有另一种解决方案 :)跨度>
【解决方案3】:

为什么不直接使用.ToList&lt;Customers&gt;()

并且不要选择订单 - 加入后您不需要它们。

List<Customer> custList =  (from c in mycontext.Customers
    join o in mycontext.Orders on c.CustomerId equals o.CustomerId
    where o.Status == 1
    select c).ToList<Customer>();

【讨论】:

    【解决方案4】:

    你需要这两个属性吗?如果是这样,遍历列表并实例化每个 curstomer...

    有点像

     List<Customer> customers = new List<Customer>();
     foreach(item in linqQuery.ToList())
     {
    
         customers.Add(item.c);
         //do something with the Order here...
     }
    

    【讨论】:

    • 您不需要.ToList()。实际上你不需要 4 行来做,但这是一个选择问题。
    【解决方案5】:
    var ledger = from c in mycontext.Customers
                     join o in mycontext.Orders on c.CustomerId equals o.CustomerId
                     where o.Status == 1
                     select new {c, o};
    
    var customers = (from row in ledger select row.Customer).Distinct().ToList();
    

    这将是我对解决方案的一种竞标(包括拼写错误等):)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-23
      • 2017-03-11
      • 2019-02-17
      • 2012-11-15
      • 2022-11-02
      • 1970-01-01
      • 2021-11-26
      • 2019-04-13
      相关资源
      最近更新 更多