Copy List

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

I have two lists of Guids:

public List<Guid> A;
public List<Guid> B;

I need to find Guids in B that do not exist in A and add them to A.

How can I do this?

Thanks,
Miguel
 
I have two lists of Guids:

public List<Guid> A;
public List<Guid> B;

I need to find Guids in B that do not exist in A and add them to A.

How can I do this?

Do a foreach loop on B and check A.Contains().
 
Jeff said:
Do a foreach loop on B and check A.Contains().
That's one way. If both A and B contain unique elements and you're using C#
3.0, you can use

A.AddRange(B.Except(A).ToArray());

Note that the .ToArray() is necessary to force evaluation before adding any
element; without it we could be modifying A while enumerating it, which is
not allowed. Thanks to the nature of the operation and the fact that it's a
list it will happen to work, but this is bad practice.

If you do not care about preserving object identity then this might be more
intuitive:

A = A.Union(B).ToList();

If there are duplicates, the results will be different. The first method
will eliminate any duplicates in B, while the second will eliminate any
duplicates in both A and B.
 
That's one way. If both A and B contain unique elements and you're using C#
3.0, you can use

   A.AddRange(B.Except(A).ToArray());

Note that the .ToArray() is necessary to force evaluation before adding any
element; without it we could be modifying A while enumerating it, which is
not allowed. Thanks to the nature of the operation and the fact that it'sa
list it will happen to work, but this is bad practice.

If you do not care about preserving object identity then this might be more
intuitive:

   A = A.Union(B).ToList();

If there are duplicates, the results will be different. The first method
will eliminate any duplicates in B, while the second will eliminate any
duplicates in both A and B.

What do you mean with preserving the object identity?

I am using Net 3.5 ...

In List A all Guids are different. In List B all Guids are different
to ...

But there can be some Guids in B that do exist in A ...
 
shapper said:
What do you mean with preserving the object identity?
If you do

A.AddRange(...);

Then A will still refer to the same object, it will just have extra
elements. If you do

A = A.Union(B).ToList();

Then you replace the reference in A with one that refers to a new object.
This can matter if you have already passed A to other code, because that
will not see your changes.
In List A all Guids are different. In List B all Guids are different
to ...

But there can be some Guids in B that do exist in A ...

This is the case I was talking about. In the end, you want A to contain the
GUIDs in both A and B.
 
Back
Top