简体   繁体   English

C#如何使用另一个集合中的对象替换一个集合中的对象

[英]C# How do I replace objects in one collection with Objects from another collection

How do I replace objects in Collection1 with a matching object(by name and description) from Collection2? 如何使用Collection2中的匹配对象(按名称和描述)替换Collection1中的对象?

Also the objects for the matching operation in Collection2 have to be within a certain range, say from 0-20. 此外,Collection2中匹配操作的对象必须在一定范围内,例如0-20。 Objects with index > 20 in Collection2 need to be appended to Collection1. Collection2中索引> 20的对象需要附加到Collection1。

    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. 我希望你得到你渴望的结果。

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... 如果你真的想要1班轮......

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();

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. 如果能够更好地理解问题,可能会采用更清洁的方式。

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;
}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM