使用LINQ对数据进行排序

时间:2011-06-10 08:00:50

标签: c# linq group-by extension-methods

这是我从数据库读入数据表的数据。

enter image description here

现在重新调整了名为table的数据表。

对于每个相同/不同的UnitType + UnitZoom + MemberZoom,我创建一个新的Unit并将MemberId读入MemberListId - 这应该在由MemberOrder的编号给出的Order中发生。样本数据:

单元1:A B C - > P1,P2
单元2:1 2 3 - > P9,P12,P4
单元3:H23 B10 T15 - > X4,T5,Z3,Y1

我现在的代码没有正确排序:

 var groupedCollection = table.AsEnumerable()
                                        .GroupBy(row => new
                                        {
                                            UType = row.Field<string>("UnitType"),
                                            UZoom = row.Field<string>("UnitZoom"),
                                            MZoom = row.Field<string>("MemberZoom"),
                                            MOrder = row.Field<int>("MemberOrder"), 
  // I DO NOT WANT the MemberOrder to be in the Group Key, but later on I use this Property to order by it... 
                                        });         


                var unitCollection = groupedCollection
                                    .Select(g => new Unit 
                                    {
                                        UnitType = g.Key.UType,
                                        UnitZoom = g.Key.UZoom,
                                        MemberZoom = g.Key.MZoom,                                   
                                        MemberIdList = g.Select(r => r.Field<string>("MemberId")).OrderBy(b => g.Key.MOrder).ToList(),
                                    });

                List<Unit> units = unitCollection.ToList(); 

1 个答案:

答案 0 :(得分:1)

按列表的静态值排序:

MemberIdList = g.Select(r => r.Field<string>("MemberId")).OrderBy(b => g.Key.MOrder).ToList()

你应该使用这样的东西:OrderBy(b => b.SomeValue)

它应该是这样的:

var groupedCollection = table.AsEnumerable()
                                    .GroupBy(row => new
                                    {
                                        UType = row.Field<string>("UnitType"),
                                        UZoom = row.Field<string>("UnitZoom"),
                                        MZoom = row.Field<string>("MemberZoom") 
                                    });         


            var unitCollection = groupedCollection
                                .Select(g => new Unit 
                                {
                                    UnitType = g.Key.UType,
                                    UnitZoom = g.Key.UZoom,
                                    MemberZoom = g.Key.MZoom,                                   
                                    MemberIdList = g.OrderBy(b => b.Field<int>("MemberOrder").Select(r => r.Field<string>("MemberId")).ToList(),
                                });

            List<Unit> units = unitCollection.ToList();