windows 10 pro office 2019 pro office 365 pro windows 10 home windows 10 enterprise office 2019 home and business office 2016 pro windows 10 education visio 2019 microsoft project 2019 microsoft project 2016 visio professional 2016 windows server 2012 windows server 2016 windows server 2019 Betriebssysteme office software windows server https://softhier.com/ instagram takipçi instagram beğeni instagram görüntüleme instagram otomatik beğeni facebook beğeni facebook sayfa beğenisi facebook takipçi twitter takipçi twitter beğeni twitter retweet youtube izlenme youtube abone instagram

Linq Orderby compares with itself. Why?

Asked By: Anonymous

Summary: when using Linq OrderBy with a comparer, I see that OrderBy compares items with themselves Compare (x, x), and I see that it compares the same items Comparer (x, y) several times.

  • Why does OrderBy Compare (x, x)?
  • Why does OrderBy compare the same item several times?

Problem description

If you have a (possibly empty) sequence of items, and you want the largest one, you could use OrderBy(...).FirstOrDefault().

I thought, it would be a waste of processing power to Order thousands of items if you will only be using the largest one. You could try to find this largest element in one enumeration, by creating some kind of Max method.

Similarly, if you search for the largest few elements: why order all items?

I heard someone say, that if you use OrderBy and take only the first element, then not the complete sequence is ordered.

So I thought to create a test program, where I order Customers using a Customer comparer. To see which Customers are comparer, the customer comparer writes the Id of the customers to the Console.

class Customer
{
    public int Id {get; set;}
    ...
}

class CustomerComparer : Comparer<Customer>
{
    public override int Compare(Customer x, Customer y)
    {
        int result = Comparer<int>.Default(x.Id, y.Id);
        Console.WriteLine("Compare {0} - {1} => {2}", x.Id, y.Id, result);
        return result;
    }
}

The console program

static void Main(string[] args)
{
    var customers = new[]
    {
        new Customer {Id = 2},
        new Customer {Id = 9},
        new Customer {Id = 6},
        new Customer {Id = 1},
        new Customer {Id = 4},
        new Customer {Id = 7},
        new Customer {Id = 3},
        new Customer {Id = 8},
        new Customer {Id = 5},
    };

    IComparer<Customer> comparer = new CustomerComparer;
    var result = customers.OrderBy(customer => customer, customerComparer).FirstOrDefault();

If I run the program I get the following output:

Compare 4 - 2 => 1
Compare 4 - 9 => -1
Compare 4 - 5 => -1
Compare 4 - 8 => -1
Compare 4 - 3 => 1
Compare 4 - 6 => -1
Compare 4 - 7 => -1
Compare 4 - 4 => 0
Compare 4 - 1 => 1
Compare 4 - 6 => -1
Compare 4 - 1 => 1
Compare 3 - 2 => 1
Compare 3 - 3 => 0
Compare 3 - 1 => 1
Compare 3 - 4 => -1
Compare 3 - 4 => -1
Compare 3 - 1 => 1
Compare 2 - 2 => 0
Compare 2 - 1 => 1
Compare 4 - 4 => 0
Compare 4 - 3 => 1
Compare 9 - 6 => 1
Compare 9 - 7 => 1
Compare 9 - 9 => 0
Compare 9 - 5 => 1
Compare 9 - 8 => 1
Compare 9 - 9 => 0
Compare 9 - 8 => 1
Compare 7 - 6 => 1
Compare 7 - 7 => 0
Compare 7 - 8 => -1
Compare 7 - 5 => 1
Compare 6 - 6 => 0
Compare 6 - 5 => 1
Compare 7 - 7 => 0
Compare 7 - 8 => -1
Compare 7 - 7 => 0

Some strange things is what I see:

  • Customer [4] is compared with itself seveal times. This is also for Customers [7] and [6], but not for Customers [8] and [1]
  • Customer [4] is compared with Customer [6], and a few comparisons later, Customer [4] is compared with Customer [6] again.
  • Customers [3] and [4] are compared twice without any other comparisons in between.
  • Double comparison is also for Customers [4] and [1], and a bit later for [4] and [3] but not for the other Customers

Why would this be an efficient sorting algorithm?


Solution

Answered By: Anonymous

As mentioned by Jeroen Mostert, it is probably comparing elements against itself to make the algorithm simpler, and simplicity can in some cases can improve performance. I would expect sorting algorithms to be fairly well optimized, so I would not worry about a few extra comparisons. Also note that Orderby is guaranteed to be stable, and this might place extra restrictions on the algorithm.

To solve the problem of returning the largest value I would suggest creating your own implementation that iterates over the collection and returns the smallest/largest. This is fairly trivial to do. Or use something like MoreLinq MaxBy / MinBy

I heard someone say, that if you use OrderBy and take only the first element, then not the complete sequence is ordered.

The internal workings of OrderBy is not documented. In theory, the runtime could inspect the whole sequence of linq calls and produce optimal code.
Edit:

  • In .Net core 3.x and later does seem to optimize this to O(n) (thanks to Matthew Watson for pointing this out).
  • In .Net framework it looks like it will create a EnumerableSorter that ends up doing a quicksort of the entire thing, presumably a stable variant. i.e. O(n log n)
  • In entity framework the query should be translated to SQL and run thru a query optimizer, probably resulting in O(n) (or better) runtime.

techinplanet staff

çanakkale escort erzincan escort van escort zonguldak escort kütahya escort osmaniye escort çorum escort giresun escort yozgat escort edirne escort uşak escort niğde escort amasya escort bolu escort kırıkkale escort karaman escort kırşehir escort sinop escort ısparta escort rize escort balıkesir escort kahramanmaraş escort trabzon escort erzurum escort batman escort elazığ escort tokat escort sivas escort mersin escort aydın escort manisa escort muğla escort tekirdağ escort urfa escort yalova escort fethiye escort

Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen windows office 365 satın al follower kaufen instagram follower kaufen porno

adana escort adapazarı escort adıyaman escort afşin escort afyon escort ağrı escort ahlat escort akçaabat escort akçakale escort akçakoca escort akdeniz escort akhisar escort aksaray escort akşehir escort aksu escort akyazı escort alanya escort alaşehir escort aliağa escort altıeylül escort altınordu escort amasya escort anamur escort ankara escort antakya escort antalya escort araklı escort ardahan escort ardeşen escort arnavutköy escort atakum escort avanos escort avcılar escort aydın escort ayvacık escort ayvalık escort aziziye escort babaeski escort bafra escort bağcılar escort bağlar escort balıkesir escort bandırma escort bartın escort batıkent escort batman escort battalgazi escort bayburt escort belek escort besni escort beylikdüzü escort beyşehir escort biga escort bilecik escort bingöl escort birecik escort bismil escort bitlis escort bodrum escort bolu escort bor escort bornova escort boyabat escort bozüyük escort buca escort bucak escort bulancak escort bulanık escort bünyan escort burdur escort bursa escort çan escort çanakkale escort canik escort çankaya escort çankırı escort çarşamba escort çayeli escort çekmeköy escort çerkeş escort çerkezköy escort çeşme escort ceyhan escort çivril escort çorlu escort çorum escort çubuk escort çukurova escort çumra escort dalaman escort darıca escort datça escort davutlar escort defne escort denizli escort derince escort develi escort didim escort digor escort dinar escort diyadin escort diyarbakır escort doğanşehir escort doğubayazıt escort dörtyol escort dulkadiroğlu escort düzce escort edirne escort edremit escort efeler escort elazığ escort elbistan escort emirdağ escort erbaa escort erdemli escort ereğli escort erenler escort ergani escort ergene escort erzincan escort erzurum escort escort esenler escort eskil escort eskişehir escort espiye escort eyyübiye escort fatih escort fatsa escort fethiye escort finike escort fındıklı escort gaziantep escort gaziemir escort gebze escort gediz escort gelibolu escort gemerek escort gemlik escort gerede escort giresun escort gölbaşı escort gölcük escort görele escort görükle escort göynük escort gümbet escort gümüşhane escort güngören escort güroymak escort gürsu escort hakkari escort haliliye escort hatay escort haymana escort horasan escort iğdır escort ilgaz escort i̇lkadım escort i̇negöl escort i̇skenderun escort isparta escort i̇stanbul escort i̇zmir escort i̇zmit escort i̇znik escort kadirli escort kadıköy escort kağıthane escort kağızman escort kahta escort kaman escort kangal escort kapaklı escort karabük escort karacabey escort karahayıt escort karaköprü escort karaman escort karatay escort karesi escort kars escort karşıyaka escort kartal escort kaş escort kastamonu escort kaynaşlı escort kayseri escort keçiören escort kemer escort kepez escort keşan escort keskin escort kestel escort kilis escort kırıkhan escort kırıkkale escort kırkağaç escort kırklareli escort kırşehir escort kızıltepe escort kocaeli escort kocasinan escort konak escort konya escort konyaaltı escort körfez escort korkuteli escort köyceğiz escort kozan escort kumluca escort kumru escort kuşadası escort kütahya escort lara escort lüleburgaz escort malatya escort malazgirt escort malkara escort maltepe escort mamak escort manavgat escort manisa escort maraş escort mardin escort marmaris escort melikgazi escort menemen escort menteşe escort meram escort mersin escort merzifon escort mezitli escort milas escort mucur escort mudanya escort mudurnu escort muğla escort muratpaşa escort muş escort mut escort nazilli escort nevşehir escort niğde escort niksar escort nilüfer escort nizip escort nurdağı escort ödemiş escort of escort oltu escort onikişubat escort ordu escort orhangazi escort ortahisar escort ortaköy escort osmancık escort osmangazi escort osmaniye escort palandöken escort pamukkale escort pamukova escort patnos escort payas escort pazar escort pazarcık escort pendik escort polatlı escort rize escort safranbolu escort şahinbey escort sakarya escort salihli escort samandağ escort samsun escort sandıklı escort şanlıurfa escort sapanca escort sarıçam escort sarıkamış escort sarıyer escort şarkışla escort şehitkamil escort selçuklu escort selim escort serdivan escort serik escort seyhan escort siirt escort silifke escort simav escort sincan escort sinop escort şişli escort sivas escort siverek escort şırnak escort söğüt escort söke escort soma escort sultangazi escort suluova escort sungurlu escort sur escort suruç escort suşehri escort susurluk escort talas escort tarsus escort taşova escort tavşanlı escort tekirdağ escort terme escort tire escort tirebolu escort tokat escort torbalı escort toroslar escort trabzon escort turgutlu escort turhal escort türkoğlu escort tuzla escort ulus escort ümraniye escort ünye escort ürgüp escort urla escort uşak escort üsküdar escort üzümlü escort van escort varto escort viranşehir escort yahşihan escort yahyalı escort yakutiye escort yalova escort yatağan escort yenişehir escort yeşilyurt escort yıldırım escort yıldızeli escort yomra escort yozgat escort yunusemre escort yüreğir escort zara escort zeytinburnu escort zile escort zonguldak escort mersin escort aydın escort manisa escort muğla escort tekirdağ escort urfa escort yalova escort fethiye escort