Linq sorts list in object initializer

95 views Asked by At

Today I've faced one very strange behavior. After creating an object with Linq query and object initializer with setting property of List<string> type the original collection and the collection that the object contains have different entries order.

public class PrintHeaderModel
{
    public List<string> Ships { get; set; }
}

...

var shipsList = new List<string>() { /* some items */ };

var model = (from inv in db.invoices
                         where inv.ListID == id && inv.RealmID == realmId
                         select new PrintHeaderModel()
                         {
                             Ships = shipsList,
                         }).FirstOrDefault();

After that the orders of entries in model.Ships and shipsList are different

Notes:

  1. db is DbContext instance (I'm using Entity Framework and MySQL database)
  2. shipsList is not sorted after it's filled
  3. If I create model object without Linq (just with "new"), the order of entries is the same in model and in the list
  4. The order becames correct if I reassign model.Ships right after model is created:

    model.Ships = shipsList; // after that the order of entries is correct
    
  5. The order of entries in model.Ships is not the same always. It changes randomly without any changes in code or database

Where was I wrong?

0

There are 0 answers