1

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(!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?

3
  • 2
    Those aren't DataSets. Commented May 11, 2011 at 16:16
  • 1
    it is possible thorugh linq if im not mistaken. stackoverflow.com/questions/2298207/… Commented May 11, 2011 at 16:19
  • Yea I know there not data sets I have made an edit to show this. Commented May 13, 2011 at 10:41

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks the Union in linq was just what I was looking for.
3

You got several alternatives.

You can concatenate them:

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

You can add one to the other:

dataSet.AddRange(dataSet2);

Comments

1

You can do something like:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.