簡體   English   中英

如何合並兩個列表的內容?

[英]How do I combine the contents of two lists?

我有兩個List<int>實例。 現在,我想將它們合並到第三個列表中。

public List<int> oldItemarry1 // storing old item
{
    get 
    { 
        return (List<int>)ViewState["oldItemarry1 "]; 
    }
    set 
    { 
        ViewState["oldItemarry1 "] = value; 
    }
}

public List<int> newItemarry1 // storing new item
{
    get
    { 
        return (List<int>)ViewState["newItemarry1 "]; 
    }
    set 
    { 
        ViewState["newItemarry1 "] = value; 
    }
}

public List<int> Itemarry1 // want to combine both the item
{
    get
    { 
        return (List<int>)ViewState["Itemarry1 "]; 
    }
    set 
    { 
        ViewState["Itemarry1 "] = value; 
    }
}

請有人告訴我該怎么做?

LINQ具有Concat方法:

return oldItemarry1.Concat(newItemarry1).ToList();

那只是把列表放在一起。 LINQ還具有Intersect方法,該方法將僅為您提供兩個列表中都存在的項目,而Except方法則僅為您提供在兩個列表中都存在的項目,但不能同時存在於兩個列表中。 Union方法為您提供兩個列表之間的所有項目,但不會像Concat方法那樣重復。

如果不是LINQ,則可以創建一個新列表,通過AddRange將每個列表中的項目添加到兩者中,然后將其返回。

編輯:

由於LINQ不是一種選擇,因此您可以通過以下幾種方法來實現:

將列表與所有項目合並,包括重復項:

var newList = new List<int>();
newList.AddRange(first);
newList.AddRange(second);
return newList

合並,沒有重復的項目

var existingItems = new HashSet<int>();
var newList = new List<int>();

existingItems.UnionWith(firstList);
existingItems.UnionWith(secondList);
newList.AddRange(existingItems);

return newList;

當然,這假定您使用的是.NET 4.0,因為那是HashSet<T>引入的時間。 您不使用Linq,真是太可惜了,它確實擅長此類事情。

使用聯合方法; 它將排除重復項。

int[] combinedWithoutDups = oldItemarry1.Union(newItemarry1).ToArray();

您可以合並兩個列表:

List<int> result = new List<int>();
result.AddRange(oldList1);
result.AddRange(oldList2);

現在,列表result具有兩個列表的所有元素。

這是一種解決方法:

public List<int> Itemarry1()
{
    List<int> combinedItems = new List<int>();

    combinedItems.AddRange(oldItemarray1);
    combinedItems.AddRange(newItemarray1);

    return combinedItems;
}

作為最佳實踐,請盡可能使用IEnumerable而不是List。 然后,為使此工作最佳,您將需要一個只讀屬性:

public IEnumerable<int> Itemarry1 // want to combine both the item
{
    get
    { 
        return ((List<int>)ViewState["oldItemarry1 "]).Concat((List<int>)ViewState["Itemarry1"]); 
    }
}

如果需要將兩個列表的時間點組合成第三個列表,則如其他人所提到的, UnionConcat是合適的。

如果要兩個列表的“實時”組合(以使對第一和第二個列表的更改自動反映在“組合”列表中),則可能需要研究Bindable LINQObtics

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM