LINQ怎么根据“某个字段”去除重复数据查询(急求答案)

LINQ怎么根据“某个字段”去除重复数据查询(急求答案),第1张

Distinct方法的第二重载可以

Enumerable.Distinct<TSource> (IEnumerable<TSource>, IEqualityComparer<TSource>),

例如数据类为

class School

{

public int Id { getset}

public string Name { getset}

//是否重点学校

public bool IsKeySchool { getset}

}

实现IEqualityComparer<School>的比较器类为

class SchoolComparer : EqualityComparer<School>

{

public override bool Equals(School x, School y)

{

return x.IsKeySchool==y.IsKeySchool

}

public override int GetHashCode(School obj)

{

return obj.IsKeySchool.GetHashCode()

}

}

原始列表为

var schoolList = new List<School>{

new School{Id=1, Name="三中",IsKeySchool=true},

new School{Id=2, Name="五中",IsKeySchool=true},

new School{Id=3, Name="十中",IsKeySchool=false},

new School{Id=4, Name="十五中",IsKeySchool=true},

new School{Id=5, Name="二十中",IsKeySchool=false},

}

执行

var tempList = schoolList.Distinct(new SchoolComparer())

结果就只有两条“三中”和“十中”

text类型就别做DISTINCT了,效率会让你吐血。

实在想做的话,尝试newslist = newslist.OrderBy(x=>x.nID).ToList().Distinct()

将数据加载入内存,用CLR来做DISTINCT

假设你上图表格数据为 DataTable dt,列分别为AA,BB,CC,DD

var query = from p in dt.AsEnumerable()

//分组

group p by new

{

t1 = p.Field<int>("AA").ToString().Substring(0, p.Field<int>("AA").ToString().Length - 2),

t2 = p.Field<double>("BB"),

t3 = p.Field<string>("CC")

} into g

select new

{

ColA = g.Key.t1,

ColB = g.Key.t2,

ColC = g.Key.t3,

ColD = g.Sum(c =>c.Field<int>("DD"))

}

//转datatable

DataTable dtNew = dt.Clone()

DataRow drNew

foreach (var p in query)

{

drNew = dtNew.NewRow()

drNew["AA"] = p.ColA

drNew["BB"] = p.ColB

drNew["CC"] = p.ColC

drNew["DD"] = p.ColD

dtNew.Rows.Add(drNew)

}

dtNew 为最终结果

注:转换过程中要考虑空值的情况


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/9541628.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-29
下一篇 2023-04-29

发表评论

登录后才能评论

评论列表(0条)

保存