user4593252
user4593252

Reputation: 3506

List's Sort Using Lambda?

What I'm trying to do is iterate over the country collection in retVal and sort each of the <StateProvinces> by Name. The hierarchy is as follows:

retVal[index].StateProvinces.ToList()[index].Name = "";

so that it is country object -> collection of states, each state has a name property and lazy loading it throwing state objects into an order based on the stateID.

What's wrong with this line of code (and why although I'm guessing I'm attempting to abuse the sort method)?

retVal[0].StateProvinces.ToList().Sort(x=>x.Name);

retVal is of type IList<Country>

Error is given for x=>x.Name:

Delegate 'System.Comparison<Country>' does not take 1 arguments

Upvotes: 0

Views: 325

Answers (3)

roblem
roblem

Reputation: 591

Ok.. I got very frustrated with this issue last night and this morning realized the real issue was that .Sort isn't there. The method you need to call to "Sort" your collections is .OrderBy.

Hopefully this helps someone to not pull out all their hair.

Upvotes: 1

Servy
Servy

Reputation: 203802

The Comparison delegate is a delegate that represents a comparison, not a projection. That is to say it takes two objects, and a result indicating which one is "smaller". You're trying to provide a projection, or a transformation of one object to another.

To write a comparison for two of these objects based on Name you'd need to write something like:

(a,b) => string.Compare(a.Name, b.Name);

You can also write a separate method to sort lists that uses a projection instead of a comparer, so that you don't need to do this for every call to Sort:

//TODO come up with a better name, but it still has to be different from `Sort`
public static void ProjectionSort<T, TKey>(
    this List<T> list,
    Func<T, TKey> selector,
    Comparer<TKey> comparer)
{
    comparer = comparer ?? Comparer<TKey>.Default;
    list.Sort((a, b) => comparer.Compare(selector(a), selector(b)));
}

Upvotes: 3

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

As error says, Comparison<T> takes two argument not one, you want something like this:

retVal[0].StateProvinces.ToList().Sort((x,y) => x.Name.CompareTo(y.Name));

Upvotes: 2

Related Questions