我试图找出是否可以使用LINQ为我提供DataTable(FirstName,LastName,QTY)中的某些数据的不同值。我可以获得不同的值并填充我的List,但是我必须运行两个不同的LINQ查询才能得到它....我相信有更好的方法可以做到这一点:)
任何建议都会受到高度赞赏(对LINQ来说很新)
代码:
public static List<StudentData> LinqDistinct(DataTable dt)
{
DataTable linqTable = dt;
//get the distinct values
var query =
(from names in dt.AsEnumerable()
select new {
FirstName = names.Field<string>("FirstName"),
LastName = names.Field<string>("LastName")
}).Distinct();
//fill my list with the distinct values
List<StudentData> sList = (from sa in query.AsEnumerable()
select new StudentData
{
FirstName = sa.FirstName,
LastName = sa.LastName
//Qty = names.Field<int>("Qty")
}).ToList();
return sList;}
答案 0 :(得分:22)
任何理由都不能简单地在distinct之后进行投影,你可能需要在Distinct之后使用AsEnumerable()但这不是什么大问题。
public static List<StudentData> LinqDistinct(DataTable dt)
{
DataTable linqTable = dt;
return
(from names in dt.AsEnumerable()
select new {
FirstName = names.Field<string>("FirstName"),
LastName = names.Field<string>("LastName")
}).Distinct().Select(x =>
new StudentData() { FirstName=x.FirstName, LastName=x.LastName})
.ToList();
}
答案 1 :(得分:5)
从您的问题中不清楚数量是您的DataTable中的值,还是给定项目的重复数量,如Ecyrb的答案。但是,如果您的StudentData
类实现了IEquatable<StudentData>
或覆盖了Equals方法,那么这应该可行:
public static List<StudentData> LinqDistinct(DataTable dt)
{
return dt.AsEnumerable()
.Select(row => new StudentData
{
FirstName = row.Field<string>("FirstName"),
LastName = row.Field<string>("LastName"),
Qty = row.Field<int>("Qty")
})
.Distinct()
.ToList();
}
如果StudentData
不支持值比较,并且您无法将该支持添加到该类,则可能必须创建IEqualityComparer<StudentData>
的实现并将其传递到Distinct
方法。
答案 2 :(得分:1)
很确定你可以这样做......
List<StudentData> sList = (from names in dt.AsEnumerable().Distinct() // I am not sure if you even have to call AsEnumerable()
select new StudentData() {
FirstName = names.Field<string>("FirstName"),
LastName = names.Field<string>("LastName")
}).ToList();
答案 3 :(得分:1)
您可以使用GroupBy
:
public static List<StudentData> LinqDistinct(DataTable dt)
{
List<StudentData> results = dt.AsEnumerable()
.GroupBy(row =>
{
FirstName = row.Field<string>("FirstName"),
LastName = row.Field<string>("LastName")
})
.Select(group => new StudentData
{
FirstName = group.Key.FirstName,
LastName = group.Key.LastName,
Qty = group.Count()
})
.ToList();
return results;
}
class StudentData
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Qty { get; set; }
}