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?
Since items is of type
IEnumerable<MyClass>, you should be able to do the following:You could even have done:
You don’t need to specify the type parameters, since they can be correctly inferred.
Edit:
items.ToDictionary(x => x.Name)is actually incorrect, becauseitemsis not of typeIEnumerable<MyClass>. It is actually anIEnumerableof the anonymouse type, that has 2 properties (Name, which contains themyClass.Nameproperty, andx, which is of typeMyClass).In that case, assuming you can do:
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.