AllStar11
AllStar11

Reputation: 175

C# Lists => Remove objects where a property does not exist in another list

I have 2 lists of the same type (Results). Both lists are populated with a unique data set but may or may not contain a common property ex: (Results.TitleName).

My question is, with an ICollection returned for each list, how can I remove items from each list where the other list does not contain Results.TitleName.

Any help would be appreciated. But keep in mind that I could be dealing with a rather large data set so performance should be considered.

var Results1 = ResultsRepository.GetPoints(FirstElement);

var Results2 = ResultsRepository.GetPoints(SecondElement);

public ICollection<Results> GetPoints(string element)
{
  if (element == null)
  {
    //Exception
  }

  using (ISession session = OpenSession())
  {
    try
    {
      return session.CreateQuery(HQL Query)
        .List<Results>();
    }
    catch (Exception ex)
    {
      //Exception
    }
  }

}

ResultsRepository is a NHibernate Domain: using System;

public class Results
{
    /// <summary>
    /// Unique Sample Number
    /// </summary>
    public virtual string SampleNumber { get; set; }

    /// <summary>
    /// Result Title name
    /// </summary>
    public virtual string TitleName{ get; set; }
}

Cheers

Upvotes: 1

Views: 2896

Answers (1)

JaredPar
JaredPar

Reputation: 754763

Try the following

List<Results> list1 = ...;
List<Results> list2 = ...;
list1.Remove(x => !list2.Any(y => y.TitleName != x.TitleName);

If you have an extremely large dataset this lookup may be too slow and hence a HashSet<T> may be preferable.

var set = new HashSet<string>(list2.Select(x => x.TitleName);
list1.Remove(x => !set.Contains(x.TitleName));

Upvotes: 3

Related Questions