Share via


How to use AddRange to add items to list distinctly?

Question

Saturday, January 12, 2013 7:28 PM

Hi,

I have a List of List of Strings, and I need to use the AddRange() Function to add set of items to it, but never duplicate items.

I used the following code :

List<List<string>> eList = new List<List<string>>();
List<List<string>> mergedList = new List<List<string>>(); 

//
// some code here
//

mergedList.AddRange(eList.Where(x => !mergedList.Contains(x)).ToList());

However it does not work.

All Duplicated items are added, so how could I solve that?

Thanks so much.

Regards,

Aya.

Aya Zoghby

All replies (4)

Saturday, January 12, 2013 9:09 PM ✅Answered | 1 vote

You can check this link below. To add unique value.

http://stackoverflow.com/questions/8652340/is-there-an-addunique-method-similar-to-addrange-for-alist-in-c-sharp

One more option..

http://stackoverflow.com/questions/14297758/add-range-of-items-to-list-without-duplication


Saturday, January 12, 2013 11:33 PM ✅Answered | 1 vote

Hi Aya,

In that case I suggest you change from using AddRange to using the linq Union query.  The example in the MSDN documentation seems to fit your case exactly

http://msdn.microsoft.com/en-us/library/bb358407.aspx

Paul Linton


Saturday, January 12, 2013 10:30 PM

What happens in 'some code here'

Each of your lists contains a collection of List<string>.  Two items which are List<string> may contain the same elements but be different lists.  For example,

var a = new List<string>{"one", "two"};

var b = new List<string>{"one", "two"};

The lists a and b are different.  An equality comparison (like the one that Conatins performs) will return false.

var c = a;

The lists a and c are the same.  An equality comparison will return true.

-OR-

Do you have duplicated items in eList?  You can produce a list of the distinct items in eList with

mergedList = eList.Distinct();

(you can add ToList() if you really need it)

-OR-

What do you consider to be duplicated?

var a = new List<List<string>> { new List<string>{"one", "two"}, new List<string>{"one", "three"}};

does a contain duplicates by your criteria?  What would the result be tht you want if this was the input?

Paul Linton


Saturday, January 12, 2013 11:02 PM

Thanks Paul,

Actually my case is the First; they are different objects, but there values are the same.

And when it happened, I need to ad just one of them to the new List , not both, even if

Regards,
Aya.

Aya Zoghby