[英]LINQ query not returning unique rows
我有此LINQ查询,该查询通过实体框架查询SQL Express数据库,但在Visual Studio中以这种方式编写时不返回唯一行:
var q = from s in _db.SD
where s.ID == ID && s.Time >= startDate && s.Time <= endDate
select s
它返回正确的行数,但每一行都具有与第一行相同的数据。 但是,当我在LinqPad中测试相同的查询时,返回的结果很好,即正确的行数和每行中的唯一数据。
其次,如果我尝试将陈述更改为:
var q = from s in _db.SD
where s.ID == ID && s.Time >= startDate && s.Time <= endDate
select s.Data
然后我得到正确的行数,并且每行都有唯一的值。 有人可以帮我找出代码问题吗?
提前致谢。 编辑:这是全部功能:
public List<SD> GetHistory(int ID, DateTime startDate, DateTime endDate)
{
var q = (from s in _db.SD
where s.ID == ID &&
s.Time >= startDate && s.Time <= endDate
select s).ToList();
return q;
}
当使用select s.Data
获取正确的不同数据时,可以编写一个在SD
类内实现IEqualityComparer<>
的Comparer
类,如下所示:
public class SD
{
public Int16 ID { get; set; }
public Byte MT { get; set; }
public Byte Data { get; set; }
public Byte SS { get; set; }
public DateTime Time { get; set; }
public class Comparer : IEqualityComparer<SD>
{
public bool Equals(SD x, SD y)
{
return x.Data == y.Data; // look...here I m using 'Data' field for distinction
}
public int GetHashCode(SD obj)
{
unchecked // overflow is fine
{
int hash = 17;
hash = hash * 23 + obj.Data.GetHashCode();
return hash;
}
}
}
}
然后,你可以写GetHistory()
方法传递Comparer
在Distinct()
方法如下:
public List<SD> GetHistory(int ID, DateTime startDate, DateTime endDate)
{
var list = new List<SD>();
var q = (from s in list
where s.ID == ID &&
s.Time >= startDate && s.Time <= endDate
select s).Distinct(new SD.Comparer()).ToList();
return q;
}
常规查询使用默认值(引用相等)检查两个对象是否相等。
因此,为了使Distinct()
以您想要的方式工作,您必须实现IEqualityComparer<T>
。 否则,它将使用默认值(引用相等)进行检查,这意味着它只会确定元素是否相同,如果它们是相同的实例,则它们是不同的。 请参阅此处的参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.