开发者

Merge two object lists in C# with LINQ

开发者 https://www.devze.com 2023-03-04 23:43 出处:网络
I have two List<T>s which are both the same type. Is there an easy way to merge to the two sets without looping though both sets and merging them into a third?

I have two List<T>s which are both the same type. Is there an easy way to merge to the two sets without looping though both sets and merging them into a third?

Code

var myObject= new List<Core.MyObject>();
var myObject2= new List<Core.MyObject>();

if(!string.IsNullOrEmpty(txb.Text))
{
    var repository = ServiceLocator.Current.GetInstance<Core.RepositoryInterfaces.IRepository>();
    myObject= repository.GetWherePostCodeLike(txb.Text).ToList();
}

if(!开发者_StackOverflow中文版string.IsNullOrWhiteSpace(ddl.SelectedValue))
{
    var repository = ServiceLocator.Current.GetInstance<Core.RepositoryInterfaces.IRepository>();
    myObject2= repository.GetNearTownX(ddlLocations.SelectedValue).ToList();
}

It would have been nice to able able to just use the += on the second, but this is not allowed... Any ideas?


Call the Concat (keeps duplicates) or Union (skips duplicates) LINQ methods

IEnumerable<MyObject> third = list.Concat(otherList);

To use Union, you'll need to override Equals and GetHashCode to compare objects by value. (or pass an IEqualityComparer<MyObject>)


You got several alternatives.

You can concatenate them:

var combined = dataSet.Concat(dataSet2).ToList();

You can add one to the other:

dataSet.AddRange(dataSet2);


You can do something like:

var merged = dataSet.Concat(dataSet2).ToList();
0

精彩评论

暂无评论...
验证码 换一张
取 消