views:

115

answers:

3

Hi All,

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!

+1  A: 

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

RossFabricant
omg - not again the old string.replace trick ... thanks!
JohnIdol
string.replace ?
Mitch Wheat
The String.Replace thing is because strings are immutable
Andreas Grech
there's a similarity in form though (even if the reason is not the same)
JohnIdol
+3  A: 

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();
Andreas Grech
This solution forces the deferred execution so that distance will be called but myStrings still won't be sorted.
trampster
Yes, that's true; I was only forcing the execution. I have updated the answer so that the returned sorted list is stored
Andreas Grech
+1  A: 

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.

trampster