开发者

ToList().Sort() in Linq query gives compilation error

I am trying to combine two SortedDictionaries, change the result to a List<KeyvaluePair<string,string>> and Sort() the result. The following statement throws an error:

var combinedEntries = from p in leftDict.Union(rightDict).ToList().Sort(myComparer) select p;

Error: Could not find an implementation of the query pattern for source type 'void'. 'Select' n开发者_如何学Cot found.

This is not working because Sort() returns void. If I split up the statement, it works:

var combinedEntries = from p in leftDict.Union(rightDict) select p;
List<KeyValuePair<string, string>> finalentries = combinedEntries.ToList();
finalentries.Sort(comparer);

I understand that sort is a method of List type and not IEnumerable, but I thought calling ToList() before Sort() will take care of that problem. So first question is can it be used like I am trying in the first statement? If not, how do I make use of orderby here?


.Sort() doesn't return a value. It sorts the list in place.

You might want to try using .OrderBy before .ToList() or, you need to end the line at .ToList() so that the list can be assigned to your variable. Then Sort.

var sortedCombined = (from p in leftDict.Union(rightDict)
                      orderby p.Key // or whatever you need
                      select p).ToList();


You can do combinedEntries = <query goes here>.OrderBy(a => a, myComparer).ToList();.
However, seperately converting it into a list, and explicitly sorting is much more readable, and I'm willing to bet some good money that List.Sort beats OrderBy in performance easily.


Sort does not return a value, and combinedEntries is going to take the result of the last called method. Since Sort returns void you are getting an error by attempting to assign void to a variable. Because of this you should keep the Sort "split up" from the rest.


Like this:

var combinedEntries = leftDict.Union(rightDict).OrderBy(kvp => kvp.Key).ToList();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜