我有以下代码。这基于使用临时容器来选择特定项,然后将它们添加到列表的末尾。
var allRoles = roles.Table
.AsEnumerable().Select(p => new FirmRole
{
Code = p.Field<string>("RoleName"),
Name = p.Field<string>("RoleName")
})ToList();
var formRoles = allRoles.Where(p => p.Code.StartsWith("f")).ToList();
var otherRoles = allRoles.Except(formRoles).ToList();
otherRoles.AddRange(formRoles);缩短代码并去掉临时列表是不是更好的方法?
就像这样
var allRoles = roles.Table
.AsEnumerable().Select(p => new FirmRole
{
Code = p.Field<string>("RoleName"),
Name = p.Field<string>("RoleName")
}).OrderBy(x=>x.Code.StartsWith("f")).ThenBy(a=>a);发布于 2015-03-23 23:05:39
在IEnumerable<T>上(如本例所示),您是对的,因为OrderBy是一种稳定的排序方法(参见Enumerable.OrderBy:此方法执行一种稳定的排序;也就是说,如果两个元素的键相等,则元素的顺序将保持不变。),因此对于具有相同键的元素,其先前的顺序将保持不变。在IQueryable<T>上,这是不能保证的。
var allRoles = roles.Table
.AsEnumerable().Select(p => new FirmRole
{
Code = p.Field<string>("RoleName"),
Name = p.Field<string>("RoleName")
}).Distinct()
.OrderBy(x => x.Item.Code.StartsWith("f"))
.ToList();请注意,您不需要二次排序,因为正如我所说的,OrderBy是稳定的。
Speedwise:你必须对小集合和大集合进行基准测试。OrderBy应为O(nlogn),但按true/false排序(如本例所示)可能更类似于O(n)
发布于 2015-03-23 23:05:00
第二个例子读起来更好。
不要认为在Distinct()之后需要.ToList()。
希望这能有所帮助
发布于 2015-03-24 00:16:59
您应该使用GroupBy和ToLookup来获得您想要的结果。
var allRoles = roles.Table
.AsEnumerable().Select(p => new FirmRole
{
Code = p.Field<string>("RoleName"),
Name = p.Field<string>("RoleName")
}).GroupBy(x => x.StartsWith("f")).ToLookup(g => g.Key);;
var formRoles = allRoles[true].ToList();
var otherRoles = allRoles[false].ToList();https://stackoverflow.com/questions/29213517
复制相似问题