繁体   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