开发者

How to sort a list<datarow>?

I have a datatable which I will convert to a list<datarow>. How do I sort the list based on some datatable column? I think it's something like list = list.Sort(p=>p.Field() but I am 开发者_如何学运维not sure about the syntax.

I am interested in using LINQ heavily so I was wondering if I should convert the datatable to a strongly typed generic list and take it from there instead of using linq to datasets. The only reason I didn't do this now is for performance reason. The datatable consists of about 20,000 records.


I'd recommend you covert the dataset to a generic list and use linq to sort:

var collection =
            from c in people
            orderby c.Name ascending
            select c;

return collection.ToList();

Where people is the generic List. There are other ways to sort using linq.

Are you always going to return 20k records? The way I understand it, there's more overhead with datatables/sets/rows than with generic lists due to all the built-in .NET functions and methods...but I might be wrong.


In general if you want to sort a List<T> you could do something like

list.Sort((a, b) => String.Compare(a.StringValue, b.StringValue));

Obviously this example is sorting string values alphabetically, but you should get the idea of the syntax to use.


You could use something like:-

list.Sort((x,y) => (int)x[i] > (int)y[i] ? 1 : ((int)x[i] < (int)y[i] ? -1 : 0))

Where i is the index of the column you want to compare. In the example above the i column contains integers. If it contained strings you could do something like

list.Sort((x,y) => string.Compare((string)x[i], (string)y[i]))

Note that the Sort method sorts the list in place, it does not create a new list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜