IEnumerable vs List - What to Use? How do they work?

后端 未结 10 2146
臣服心动
臣服心动 2020-11-22 03:57

I have some doubts over how Enumerators work, and LINQ. Consider these two simple selects:

List sel = (from animal in Animals 
                         


        
10条回答
  •  醉酒成梦
    2020-11-22 04:27

    I will share one misused concept that I fell into one day:

    var names = new List {"mercedes", "mazda", "bmw", "fiat", "ferrari"};
    
    var startingWith_M = names.Where(x => x.StartsWith("m"));
    
    var startingWith_F = names.Where(x => x.StartsWith("f"));
    
    
    // updating existing list
    names[0] = "ford";
    
    // Guess what should be printed before continuing
    print( startingWith_M.ToList() );
    print( startingWith_F.ToList() );
    

    Expected result

    // I was expecting    
    print( startingWith_M.ToList() ); // mercedes, mazda
    print( startingWith_F.ToList() ); // fiat, ferrari
    

    Actual result

    // what printed actualy   
    print( startingWith_M.ToList() ); // mazda
    print( startingWith_F.ToList() ); // ford, fiat, ferrari
    

    Explanation

    As per other answers, the evaluation of the result was deferred until calling ToList or similar invocation methods for example ToArray.

    So I can rewrite the code in this case as:

    var names = new List {"mercedes", "mazda", "bmw", "fiat", "ferrari"};
    
    // updating existing list
    names[0] = "ford";
    
    // before calling ToList directly
    var startingWith_M = names.Where(x => x.StartsWith("m"));
    
    var startingWith_F = names.Where(x => x.StartsWith("f"));
    
    print( startingWith_M.ToList() );
    print( startingWith_F.ToList() );
    

    Play arround

    https://repl.it/E8Ki/0

提交回复
热议问题