How to remove range of elements from the list based upon the selection of the other list?

Suppose you have List A of type MyType {int SourceId, int Id, string value} and List B of the same type.
You want to remove all the elements in List B where ListB.MyType.Id == ListA.MyType.Id.

How to do it in C# in most elegant way?

Thanks.
LVL 1
chuang4630Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Najam UddinCommented:
ListA.RemoveAll(x => ListB.Contains(x.SourceId));

Open in new window

0
chuang4630Author Commented:
There is type conversion error
0
Fernando SotoRetiredCommented:
Hi chuang4630;

Try this, it should do what you want.
ListB.RemoveAll(b => ListA.Any(a => a.Id == b.Id));

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
it_saigeDeveloperCommented:
If you want to do this in this way, you have to implement IComparable, ICloneable and IEquatable on your class; e.g. -
using System;
using System.Collections.Generic;
using System.Linq;

namespace EE_Q28854299
{
	class Program
	{
		static List<Element> A = new List<Element>(from i in Enumerable.Range(0, 100) select new Element() { ID = i, SourceID = i % 3, Value = string.Format("Value{0}", i) });
		static List<Element> B = new List<Element>(from i in Enumerable.Range(0, 100) where i % 3 == 0 select new Element() { ID = i, SourceID = i % 3, Value = string.Format("Value{0}", i) });
		static void Main(string[] args)
		{
			Console.WriteLine("A has {0} elements.", A.Count());
			// I would personally prefer to use .Except()
			// A = A.Except(B).ToList();
			// But this will work as well.
			A.RemoveAll(x => B.Contains(x));
			Console.WriteLine("A now has {0} elements.", A.Count());
			Console.ReadLine();
		}
	}

	class Element : IComparable, ICloneable, IComparable<Element>, IComparer<Element>, IEquatable<Element>
	{
		public int ID { get; set; }
		public int SourceID { get; set; }
		public string Value { get; set; }

		public Element() { ;}

		public Element(Element source)
		{
			ID = source.ID;
			SourceID = source.SourceID;
			Value = source.Value;
		}

		public int Compare(Element x, Element y)
		{
			if (x == y)
				return 0;
			return x.ID.CompareTo(y.ID);
		}

		public int CompareTo(object obj)
		{
			return CompareTo(obj as Element);
		}

		public int CompareTo(Element other)
		{
			return Compare(this, other);
		}

		public object Clone()
		{
			return new Element(this);
		}

		public override bool Equals(object obj)
		{
			if (this == null)
				throw new NullReferenceException();

			if (obj == null || (obj.GetType() != GetType()))
				return false;

			return Equals(obj as Element);
		}

		public bool Equals(Element other)
		{
			if (Object.ReferenceEquals(this, null))
				throw new NullReferenceException();

			if (Object.ReferenceEquals(other, null))
				return false;

			if (Object.ReferenceEquals(other, this))
				return true;

			return Object.Equals(ID, other.ID) && Object.Equals(SourceID, other.SourceID) && Object.Equals(Value, other.Value);
		}

		public override int GetHashCode()
		{
			return ID.GetHashCode() ^ SourceID.GetHashCode() ^ Value.GetHashCode();
		}

		public static bool operator ==(Element lhs, Element rhs)
		{
			return Object.Equals(lhs, rhs);
		}

		public static bool operator !=(Element lhs, Element rhs)
		{
			return lhs != rhs;
		}
	}
}

Open in new window

Which produces the following output -Capture.JPGOtherwise, you would have to use a intermediary or outer-inner reverse loops (simply because the elements contained in each list are not equal to each other).
Proof of concept:
using System;
using System.Collections.Generic;
using System.Linq;

namespace EE_Q28854299
{
	class Program
	{
		static List<Element> A = new List<Element>(from i in Enumerable.Range(0, 100) select new Element() { ID = i, SourceID = i % 3, Value = string.Format("Value{0}", i) });
		static List<Element> B = new List<Element>(from i in Enumerable.Range(0, 100) where i % 3 == 0 select new Element() { ID = i, SourceID = i % 3, Value = string.Format("Value{0}", i) });
		static void Main(string[] args)
		{
			Console.WriteLine("A has {0} elements.", A.Count());
			A.RemoveAll(x => B.Contains(x));
			Console.WriteLine("A now has {0} elements.", A.Count());
			A = A.Except(B).ToList();
			Console.WriteLine("Hmmm, same count, lets try Except: {0} elements", A.Count());
			A = RemoveMatches(A, B);
			Console.WriteLine("Have to resort to an intermediary: {0}", A.Count());
			Console.ReadLine();
		}

		private static List<Element> RemoveMatches(List<Element> target, List<Element> source)
		{
			// The linq version:
			//target.RemoveAll(x => (from a in target from b in source where b.ID == a.ID select a).Contains(x));
			//return target;
			// -or-
			//return target.Except(from a in target from b in source where b.ID == a.ID select a).ToList();

			foreach (var a in target.Reverse<Element>())
			{
				foreach (var b in source.Reverse<Element>())
				{
					if (b.ID == a.ID)
						target.Remove(a);
				}
			}
			return target;
		}
	}

	class Element
	{
		public int ID { get; set; }
		public int SourceID { get; set; }
		public string Value { get; set; }
	}
}

Open in new window

Which now produces this output -Capture.JPG-saige-
0
it_saigeDeveloperCommented:
Or as Fernando has stated.  ;)

-saige-
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.