C# LINQ 获取不同的值并填充 LIST

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1786770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:49:21  来源:igfitidea点击:

LINQ Get Distinct values and fill LIST

c#linq

提问by scarpacci

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 :)

我想弄清楚是否可以使用 LINQ 为我提供 DataTable 中某些数据的不同值(名字、姓氏、数量)。我可以获取不同的值并填充我的列表,但我必须运行两个不同的 LINQ 查询才能获取它......我相信有更好的方法来做到这一点:)

Any suggestions would be greatly appreciated (very new to LINQ)

任何建议将不胜感激(对 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;}

采纳答案by ShuggyCoUk

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.

任何不简单地在 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();
}

回答by bytebender

Pretty sure you could just do this...

很确定你可以做到这一点......

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();

回答by Ecyrb

You could use GroupBy:

你可以使用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; }
}

回答by Joel Mueller

It's not clear from your question whether the quantity is a value in your DataTable, or a count of the number of duplicates for a given item, as in Ecyrb's answer. However, if your StudentDataclass implements IEquatable<StudentData>or overrides the Equals method, this should work:

从您的问题中不清楚数量是您的 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();
}

If StudentDatadoesn't support value comparison, and you can't add that support to the class, you may have to create an implementation of IEqualityComparer<StudentData>and pass that into the Distinctmethod.

如果StudentData不支持值比较,并且您无法向类添加该支持,则可能必须创建 的实现IEqualityComparer<StudentData>并将其传递到Distinct方法中。