Reputation: 67
I have entity which is as follows
public class A
{
public virtual int Id { get; set; }
public virtual string AccountName { get; set; }
public virtual string AccountId { get; set; }
public virtual Status Status { get; set; }
public virtual IList<Service> Services { get; set; }
}
I have another list which is of type Services which i want to compare with entity A.Services and get only those results of A which are matching (the same).
I want a lambda express or some way
Upvotes: 0
Views: 1479
Reputation: 1123
Why not just have a method on class A that does it, then you don't need to bother with IEquatable...
public class A
{
public virtual int Id { get; set; }
public virtual string AccountName { get; set; }
public virtual string AccountId { get; set; }
public virtual Status Status { get; set; }
public virtual IList<Service> Services { get; set; }
public List<Service> GetCommonServices(A compareTo)
{
return this.Services.Intersect(compareTo.Services);
}
}
Upvotes: 0
Reputation: 16277
You can have you class implement IEquatable, and then use Linq Intersect.
public class A : IEquatable<A>
{
public virtual int Id { get; set; }
public virtual string AccountName { get; set; }
public virtual string AccountId { get; set; }
public virtual Status Status { get; set; }
public virtual IList<Service> Services { get; set; }
//Implement IEquatable interfaces
//...
}
Note that when using LINQ Intersection call, use below one:
public static IEnumerable<TSource> Intersect<TSource>(
this IEnumerable<TSource> first,
IEnumerable<TSource> second,
IEqualityComparer<TSource> comparer) // <--- This is important
Upvotes: 2
Reputation: 63065
Implement IEquatable<Service>
and then you can use Intersect
as below
var common = services1.Intersect(services2);
Upvotes: 0
Reputation: 98750
You can use Enumerable.Intersect
method.
Produces the set intersection of two sequences by using the default equality comparer to compare values.
public class A : IEquatable<Service>
{
public virtual int Id { get; set; }
public virtual string AccountName { get; set; }
public virtual string AccountId { get; set; }
public virtual Status Status { get; set; }
public virtual IList<Service> Services { get; set; }
}
var commonListofService = services1.Intersect(services2);
Upvotes: 1