2010-02-09 129 views
2

这个简单的Linq查询:如何将一个匿名类型的列表转换为列表<T>?

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<Customer>)?

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

+3

你需要在所有或订单八九不离十招标?如果不是,您可以只选择“c”而不是“选择新的{c,o}” – cyberzed 2010-02-09 13:07:20

+2

如果您只需要客户,您为什么加入订单? – 2010-02-09 13:18:46

回答

7
result.Select(o => o.Customer).ToList(); 

这是你的意思吗?

+1

这将返回每个客户'X'次,其中'X'是与每个客户关联的订单数量。你的答案没有错,但也许他想要独特的客户,他更好地知道这个例子并没有这样做。 – 2010-02-09 13:09:37

+0

好点。问题是为什么有订单加入? 无论如何,你仍然可以打电话.Distinct(),如果有必要... – RoelF 2010-02-09 13:24:51

+0

这不是最简单的方式,虽然 – 2010-02-09 13:44:49

1

非常基本的方法,因为你explecitely问:“什么是转换匿名类型[...]最简单的方法”:

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 

也许你可以给我们一些更多的信息,你想要什么完全可以实现!

+0

我想尽可能简单地将我的Linq查询的结果转换为列表。 – 2010-02-09 13:01:26

+0

为**这个**列表,我给你答案...如果你想要一个更一般的(又名通用)答案,可能有另一个解决方案:) – 2010-02-09 13:02:43

0

您是否需要这两个属性?如果通过列表,以便步骤,并分别给出curstomer ...

喜欢的东西

List<Customer> customers = new List<Customer>(); 
foreach(item in linqQuery.ToList()) 
{ 

    customers.Add(item.c); 
    //do something with the Order here... 
} 
+2

你不需要'.ToList()'。其实你不需要4条线来做,但这是一个选择的问题。 – 2010-02-09 13:12:43

2

为什么不直接使用.ToList<Customers>()

,并没有选择订单 - 你不需要他们之后加入。

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

这将是我的一个解决方案(包括mispellings等):)

相关问题