Domanda

I am trying to sort some strings using entity framework OrderByDescending or OrderBy but some how it is not working, i need to use sort with string comparer.

Here is my Code:

public class MyStringComparer : IComparer<string> 
{
    CultureInfo culture = new System.Globalization.CultureInfo("no");
    public int Compare(string x, string y)
    {
            return string.Compare(x, y, true, culture);
    }
}
class Program
{
    static void Main(string[] args)
    {
        MyStringComparer comparer = new MyStringComparer();
        List<string> name = new List<string> { "åtestå", "aaabc", "åtestå", "Basxas","xxxax" };
        name.OrderByDescending(x => x, comparer);
        name.ForEach( x => {
            Console.WriteLine(x);
        });
        Console.ReadKey();
    }
}

Comparer is never called, what am I missing?

Result should be

aaabc
Basxas
xxxax
åtestå
åtestå

But it is coming as

åtestå
aaabc
åtestå
Basxas
xxxax

If there could be another way to do the same, please suggest.

È stato utile?

Soluzione

You might want to read up on LINQ deferred execution.

Replace:

name.OrderByDescending(x=> x, comparer);
name.ForEach(x => { Console.WriteLine(x); });

With:

var ordered = name.OrderByDescending(x=> x, comparer).ToList();
ordered.Foreach(Console.WriteLine);

Explanation:

name.OrderByDescending(x => x, comparer) returns an IEnumerable<String> and the comparer is not utilized until the collection is enumerated. You are however not storing the result of this operation, so it never happens.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top