C# How do I replace objects in one collection with Objects from another collection
10,707
Solution 1
This is one way:
foreach (var item in collection2.Take(20)) // grab replacement range
{
int index;
if ((index = collection1.FindIndex(x =>
x.Name == item.Name &&
x.Description == item.Description)) > -1)
{
collection1[index] = item;
}
}
collection1.AddRange(collection2.Skip(20)); // append the rest
It's highly likely that the code can be improved even more, if your intentions were a little more clear. There may be a cleaner way if the problem was better understood.
Solution 2
List<MyClass> mainList = new List<MyClass>();
List<MyClass> childList = new List<MyClass>();
foreach (MyClass myClass in childList)
{
int index = mainList.FindIndex(delegate(MyClass item) { return (item.Name==myClass.Name && ; item.Description == myClass.Description);});
mainList[index] = myClass;
}
Try this one. I hope you get your desire result.
Solution 3
List<MyClass> originalCollection = new List<MyClass>();
List<MyClass> newStuff = new List<MyClass>();
foreach (var item in newStuff)
{
int index = originalCollection.FindIndex(x => x.Name == item.Name && x.Description == item.Description);
if (index < 0)
continue;
originalCollection[index] = item;
}
If your really want a 1-liner...
List<MyClass> originalCollection = new List<MyClass>();
List<MyClass> newStuff = new List<MyClass>();
originalCollection = newStuff.Concat(originalCollection.Where(x => !newStuff.Any(y => y.Description == x.Description && y.Name == x.Name)).ToArray()).ToList();
Solution 4
One way in extension Method
public static void Replace(this object[] elements, object oldObject, object newObject) {
var index = elements.IndexOf(oldObject);
if (index > 0) {
elements[index] = newObject;
}}
Author by
john smith
Updated on June 05, 2022Comments
-
john smith almost 2 years
How do I replace objects in Collection1 with a matching object(by name and description) from Collection2?
Also the objects for the matching operation in Collection2 have to be within a certain range, say from 0-20. Objects with index > 20 in Collection2 need to be appended to Collection1.