LINQ Query with grouping and ranking

前端 未结 5 1688
醉话见心
醉话见心 2021-01-13 20:32

I have a sql table called predictions with data as below

Week    Player     Points
201101  Mark       7
201101  Mark       7
201101  Pete       7
201101  Pet         


        
5条回答
  •  抹茶落季
    2021-01-13 20:59

    Just pass a datatable to following function (Please note that the code is in c#) //dt should contain column points but not rank column

     public static DataTable GetRankedDatatable(DataTable dt)
                {
                    var rankedDt = (from row in dt.AsEnumerable()
                                    orderby row.Field("points")
                                    select row).CopyToDataTable();
                    rankedDt.Columns.Add("rank");
                    int rank = 0;
                    for (int i = 0; i < rankedDt.Rows.Count - 1; i++)
                    {
                        rankedDt.Rows[i]["rank"] = rank;
                        if (rankedDt.Rows[i]["points"].ToString() != rankedDt.Rows[i + 1]["points"].ToString())
                        {
                            rank++;
                        }
                    }
                    rankedDt.Rows[rankedDt.Rows.Count - 1]["rank"] = rank;
                    return rankedDt;
                }
    

提交回复
热议问题