views:

347

answers:

1

I am using WCF REST Preview 2 to test some REST services. The package has an extension to IEnumerable as ToDictionary(Func(TSource, TKey) keySelctor. Not sure how to define a lambda function to return keySelector?

Here is one example:

 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

Not sure what should be the lambda Func should be to return a KeySelector?

+1  A: 

Since items is of type IEnumerable<MyClass>, you should be able to do the following:

items.ToDictionary(x => x.Name)

You could even have done:

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

You don't need to specify the type parameters, since they can be correctly inferred.

Edit:

items.ToDictionary(x => x.Name) is actually incorrect, because items is not of type IEnumerable<MyClass>. It is actually an IEnumerable of the anonymouse type, that has 2 properties (Name, which contains the myClass.Name property, and x, which is of type MyClass).

In that case, assuming you can do:

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

The second example is a bit easier to use in this case. Essentially, you don't get any value from the linq query to get items, if all you're trying to do is generate a dictionary.

Nader Shirazie
Thanks. It works.
David.Chu.ca