LINQ查询不返回唯一行

时间:2014-02-23 04:22:51

标签: c# linq

我有这个LINQ查询,它通过Entity Framework查询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;
}

1 个答案:

答案 0 :(得分:0)

当您使用select s.Data获取正确的不同数据时,您可以在Comparer类中编写实现IEqualityComparer<>的{​​{1}}类,如下所示:

SD

然后您可以在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; } 。否则,它将使用默认(引用相等)进行检查,这意味着只有在它们是完全相同的实例时才会确定元素不是不同的。 See the reference here.

相关问题