[英]Comparing two list C#
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). 我有另一个服务类型的列表,我想与实体A.Services进行比较,并仅获取匹配(相同)的A结果。
I want a lambda express or some way 我想要Lambda Express或其他方式
You can have you class implement IEquatable, and then use Linq Intersect. 您可以让您的类实现IEquatable,然后使用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: 请注意,在使用LINQ Intersection调用时,请使用以下一项:
public static IEnumerable<TSource> Intersect<TSource>(
this IEnumerable<TSource> first,
IEnumerable<TSource> second,
IEqualityComparer<TSource> comparer) // <--- This is important
You can use Enumerable.Intersect
method. 您可以使用
Enumerable.Intersect
方法。
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);
实现IEquatable<Service>
,然后您可以按以下方式使用Intersect
var common = services1.Intersect(services2);
Why not just have a method on class A that does it, then you don't need to bother with IEquatable... 为什么不只在类A上有一个做到这一点的方法,那么您就不必费心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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.