簡體   English   中英

C#如何使用另一個集合中的對象替換一個集合中的對象

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

如何使用Collection2中的匹配對象(按名稱和描述)替換Collection1中的對象?

此外,Collection2中匹配操作的對象必須在一定范圍內,例如0-20。 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;
    }

試試這個吧。 我希望你得到你渴望的結果。

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

如果你真的想要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();

這是一種方式:

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

如果您的意圖更加明確,那么代碼很可能會得到更多改進。 如果能夠更好地理解問題,可能會采用更清潔的方式。

擴展方法的一種方法

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