C# 如何在fluent LINQ中比较两个列表对象
我有两个列表,它们有不同类型的对象C# 如何在fluent LINQ中比较两个列表对象,c#,.net,C#,.net,我有两个列表,它们有不同类型的对象 List<Type1> list1 List<Type2> list2 谢谢您可以加入多个字段,但您需要其他内容来存储它们的值 假设Type1和Type2之间的其他属性都不同,则需要第三个类来存储要保留的信息 var results = (from l1 in list1 join l2 in list2 on new { l1.ID, l1.Date} equals new { l2.ID, l2.Date }
List<Type1> list1
List<Type2> list2
谢谢您可以加入多个字段,但您需要其他内容来存储它们的值 假设
Type1
和Type2
之间的其他属性都不同,则需要第三个类来存储要保留的信息
var results
= (from l1 in list1
join l2 in list2 on new { l1.ID, l1.Date} equals new { l2.ID, l2.Date }
select new SomeThirdClass { });
如果要使用扩展方法,可以使用.Join()方法
创建公共基类或接口,并为其实现IEqualityComparer
public class BaseClass
{
public int Id;
public DateTime Date;
}
class Type1: BaseClass
{
}
class Type2 : BaseClass
{
}
public class BaseClassComparer : IEqualityComparer<BaseClass>
{
#region IEqualityComparer<BaseClass> Members
public bool Equals( BaseClass x, BaseClass y )
{
return x.Id == y.Id && x.Date == y.Date;
}
public int GetHashCode( BaseClass obj )
{
return obj.GetHashCode ();
}
#endregion
}
公共类基类
{
公共int Id;
公共日期时间日期;
}
类类型1:基类
{
}
类类型2:基类
{
}
公共类基类比较器:IEqualityComparer
{
#地区资格比较成员
公共布尔等于(基类x,基类y)
{
返回x.Id==y.Id&&x.Date==y.Date;
}
public int GetHashCode(基类obj)
{
返回obj.GetHashCode();
}
#端区
}
然后简单地使用Intersect()和比较器创建一个包含不同对象的合并列表
List<Type1> t1 = new List<Type1>();
List<Type2> t2 = new List<Type2>();
var combined = t1.Intersect( t2, new BaseClassComparer() );
List t1=新列表();
列表t2=新列表();
var combined=t1.Intersect(t2,新的BaseClassComparer());
创建一个公共接口(或基类)…然后使用Join()
查看示例或代码的答案..如何用流畅的语法编写此代码?是否要使用.Intersect
而不是.Union
?@agarwaen-同样。
public class BaseClass
{
public int Id;
public DateTime Date;
}
class Type1: BaseClass
{
}
class Type2 : BaseClass
{
}
public class BaseClassComparer : IEqualityComparer<BaseClass>
{
#region IEqualityComparer<BaseClass> Members
public bool Equals( BaseClass x, BaseClass y )
{
return x.Id == y.Id && x.Date == y.Date;
}
public int GetHashCode( BaseClass obj )
{
return obj.GetHashCode ();
}
#endregion
}
List<Type1> t1 = new List<Type1>();
List<Type2> t2 = new List<Type2>();
var combined = t1.Intersect( t2, new BaseClassComparer() );