Search code examples
c#linqilist

Update IList data


I have used two IList object. In first list, it contains 10 records and the second contains 5 records. Now I want to update the first IList with second IList data.

foreach (ObjList newlist in New)
{
    ObjList list = ExtList.FirstOrDefault(x => x.Id == newlist.Id);

    if (list!= null)
    {
        ExtList.Remove(list);
        ExtList.Add(newlist);
    }
}

I tried the above. But the added object appended at the end of the list. So sort order changed. I need it in the same existing order.

Updated

I tried the sorting, but it is not sorted.

ExtList.OrderBy(x => x.Id);

Solution

  • You can try using IList.Insert() to add new item at the index of to-be-replaced item, so that you can keep the list in it's original order :

    ObjList list = ExtList.FirstOrDefault(x => x.Id == newlist.Id);
    
    if (list!= null)
    {
        var position = ExtList.IndexOf(list);
        ExtList.Insert(position, newlist);
        ExtList.Remove(list);
    }