2012-06-15 67 views
1

的方式,我有这样的代码:我的LINQ排序似乎并没有被选我要求它

var query = _cityRepository.GetAll(
           u => u.PartitionKey == pk & 
           u.RowKey.CompareTo(lowerBound) >= 0 & 
           u.RowKey.CompareTo(upperBound) < 0) 
       .OrderBy(item => item.RowKey.Substring(0, 3)) 
       .ThenBy(item => item.ShortTitle) 
       .Select((t, index) => new City.Grid() 
       { 
        PartitionKey = t.PartitionKey, 
        RowKey = t.RowKey, 
        Row = index + 1, 
        ShortTitle = t.ShortTitle, 
        Created = t.Created, 
        CreatedBy = t.CreatedBy, 
        Modified = t.Modified, 
        ModifiedBy = t.ModifiedBy 
       }) 
       .ToList(); 

当我看到数据出来我觉得这是对前两行:

RowKey = 0101004O , ShortTitle = "Access 1" 
RowKey = 0103004M , ShortTitle = "Access 2" 
RowKey = 0101004K , ShortTitle = "xxx" 

当测试我简化了这个给:

 var query1 = _cityRepository.GetAll() 
      .OrderBy(item => item.RowKey.Substring(0, 3)) 
      .ThenBy(item => item.ShortTitle); 

和顺序是相同的。仍然RowKey似乎没有正确的顺序。

它应该排序的rowkey的前四个字符,然后在ShortTitle。

任何人都可以明白为什么这是行不通的。我看过很难,但我不明白为什么排序依据和ThenBy似乎并没有正常工作。

+0

这个错误可能在这里:** item.RowKey.Substring(0,3)**。我认为它应该是** item.RowKey.Substring(0,4)** –

+0

谢谢大家! – Alan2

回答

5

你通过rowkey的前3个字符,而不是4排序要使用4个字符,这样做:

 .OrderBy(item => item.RowKey.Substring(0, 4)) 
+0

D'哦!我正要发布一些无聊的约'子串()'捕捉关闭! –

+0

感谢。我看着谷歌,并看到不同的子字符串。我可能会不小心寻找java :-(我会标记你的答案是正确的。 – Alan2

2

Substring的第二个参数是length,没有指标,我相信这是什么你的代码正在尝试去做。您的代码在当前状态下是基于前三个字符进行排序的。变化:

.OrderBy(item => item.RowKey.Substring(0, 3)) 

.OrderBy(item => item.RowKey.Substring(0, 4)) 
1

你的子更改为子串(0,4),如果你想获得4个字符。第二个参数指定长度不是索引