2009-08-27 72 views
0

我正在使用WCF REST Preview 2来测试一些REST服务。 ?包装上有一个扩展的IEnumerable为ToDictionary(Func键(TSource,TKEY的)keySelctor不知道如何定义lambda函数返回的KeySelectorsWCF REST扩展到IEnumerable Lambda Func <TSource,TKey> keySelector

下面是一个例子:

var items = from x in entity.Instances // a customized Entity class with list instances of MyClass 
      select new { x.Name, x}; 
Dictionary<string, MyClass> dic = items.ToDictionary<string, MyClass>(
     (x, y) => ... // what should be here. I tried x.Name, x all not working 

不知道应该怎样?将拉姆达函数功能应该是返回一个KeySelector

回答

1

由于项目是IEnumerable<MyClass>类型的,你应该能够做到以下几点:

items.ToDictionary(x => x.Name) 

你甚至可以这样做:

entity.Instances.ToDictionary(x => x.Name) 

你不需要指定类型参数,因为它们可以正确地推断。

编辑:

items.ToDictionary(x => x.Name)实际上是不正确的,因为itemsIEnumerable<MyClass>类型的不行。它实际上是anonymouse类型的IEnumerable,它具有2个属性(Name,其中包含myClass.Name属性和x,它的类型为MyClass)。

在这种情况下,假设你可以这样做:

var items = from instance in entity.Instances 
      select new { Name = instance.Name, // don't have to specify name as the parameter 
         Instance = instance 
         }; 

var dict = items.ToDictionary(item => item.Name, 
           item => item.Instance); 

第二个例子是一个有点容易在这种情况下使用。从本质上讲,如果你所要做的只是生成一个字典,你不会从linq查询中获得任何价值来得到items

+0

谢谢。有用。 – 2009-08-27 22:20:15

相关问题