LINQ获取不同的值,并填写LIST [英] LINQ Get Distinct values and fill LIST
问题描述
我想弄清楚,如果我可以使用LINQ向我提供一些数据我有一个DataTable(名字,姓氏,QTY)的不同的值。我可以得到不同的值,并填写我的名单,但我必须运行两个不同的LINQ查询得到它....我敢肯定有一个更好的方式来做到这一点:)
任何建议,将不胜感激(很新的LINQ)
代码:
公共静态列表< StudentData> LinqDistinct(数据表DT)
{
DataTable的linqTable = DT;
//获取不同的值
VAR的查询=
(从名称中dt.AsEnumerable()
选择新{
名字= names.Field< ;串>(名字),
姓氏= names.Field<字符串方式>(姓氏)
})是不同的();
//填满我的列表与不同的值
名单,LT; StudentData> SLIST =(从query.AsEnumerable()
SA选择新StudentData
{
名字= sa.FirstName,
姓氏= sa.LastName
//数量= names.Field< INT>(数量)
})了ToList()。
返回SLIST;}
任何理由不只是做投影的不同后,你可能需要一个AsEnumerable()的鲜明后,但是这并不是什么大不了的事。
公共静态列表< StudentData> LinqDistinct(数据表DT)
{
DataTable的linqTable = DT;
返回
(从dt.AsEnumerable名()
选择新{
名字= names.Field<串>(名字),
姓氏=名称技术领域<串>(姓氏)
})是不同的()选择(X =>
新StudentData(){名字= x.FirstName,姓氏= x.LastName})
.ToList();
}
I am trying to figure out if I can use LINQ to provide me with the distinct values of some data I have in a DataTable (FirstName, LastName, QTY). I can get the distinct values and fill my List, but I have to run two different LINQ queries to get it....I am sure there is a better way to do it :)
Any suggestions would be greatly appreciated (very new to LINQ)
Code:
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;}
Any reason not to simply do the projection after the distinct, you might need an AsEnumerable() after the Distinct but that's not a big deal.
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();
}
这篇关于LINQ获取不同的值,并填写LIST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!