JohnIdol
JohnIdol

Reputation: 50127

List ordering - Extension method not firing!

I am trying to sort a List like this:

public void Example()
{
    string target = "hello";

    List<string> myStings = new List<string>();

    myStings.Add("babab");
    myStings.Add("Helll");
    myStings.Add("atest");

    myStings.OrderBy(each => Distance(each, target));
}

public int Distance(string stringA, string stringB)
{
    // Whatever
}

The problem is that the list doesn't get ordered and the Distance method doesn't get fired (I put a breakpoint in there but doesn't get hit).

Any help appreciated!

Upvotes: 1

Views: 202

Answers (3)

trampster
trampster

Reputation: 8918

your

myStrings.OrderBy(each => Distance(each, target));

wont order your original list it return a ordered list. You need:

myStrings = myStrings.OrderBy(each => Distance(each, target)).ToList();

this will force the deferred execution to take place and give you the result you require.

Upvotes: 1

Andreas Grech
Andreas Grech

Reputation: 107990

This is because of Linq's Deferred Execution

In LINQ, execution of a query is usually deferred until the moment when you actually request the data.

So, to see your method working, apply the ToList() method to your IOrderedEnumerable so that you will actually be requesting the data, and thus the execution takes place.

myStings = myStings.OrderBy(each => Distance(each, target)).ToList();

Upvotes: 3

RossFabricant
RossFabricant

Reputation: 12492

myStings = myStings.OrderBy(each => Distance(each, target)).ToList();

Upvotes: 1

Related Questions