我有以下查询。有没有一种简单的方法可以按数字顺序对结果进行排序 RowKey目前RowKey是一个字符串。我想排序_rowData而不是修改这个查询,因为我想尝试一些不同的排序顺序,我正在寻找一行更改而不是重做查询。
var _rowData = (from qu in _que.GetAll(
u => u.PartitionKey == partitionKey )
select new {
qu.PartitionKey,
qu.RowKey,
qu.Style,
qu.ShortTitle,
ModifiedToString = String.Format("{0:MM/dd/yyyy HH:mm}", qu.Modified)
});
我想在LINQ查询之外进行排序。原因是实际上我希望能够让用户选择一种RowKey,ModifiedToString和ShortTitle。
答案 0 :(得分:1)
当您使用OrderBy扩展名时,您不会修改原始查询,它只是枚举相同的值:
var _rowData = ...
var _rowDataSortedByRowKey = _rowData.OrderBy( u => u.RowKey );
var _rowDataSortedByModifiedToString = _rowData.OrderBy( u => u.ModifiedToString );
var _rowDataSortedByShortTitle = _rowData.OrderBy( u => u.ShortTitle );
var _rowDataSortedByOther = _rowData.OrderBy( ... );
答案 1 :(得分:0)
您可以使用orderby关键字订购LINQ查询的元素:
OrderBy - 简单2
此示例使用orderby按长度对单词列表进行排序。
public void Linq29() { string[] words = { "cherry", "apple", "blueberry" }; var sortedWords = from w in words orderby w.Length select w; Console.WriteLine("The sorted list of words (by length):"); foreach (var w in sortedWords) { Console.WriteLine(w); } }
排序的单词列表(按长度排列):
apple cherry
您还可以使用Enumerable.OrderBy Extension Method:
var sortedWords = words.OrderBy(w => w.Length);
如果您想按不同的标准订购,可以为每个标准传递不同的密钥选择器:
if (c == "Length")
sortedWords = words.OrderBy(w => w.Length);
else
sortedWords = words.OrderBy(w => w);
答案 2 :(得分:0)
这里你去:
_rowData.Sort((a, b) => Convert.ToInt32(a.Key).CompareTo(Convert.ToInt32(b.Key)));
答案 3 :(得分:0)
尝试在Distinct语句中指定DataRowComparer.Default。
示例:
var query = (from c in functiongettable().AsEnumerable()
orderby c.Field<string>("Name")
select c).Distinc(DataRowComparer.Default);
答案 4 :(得分:0)
您可以使用System.Linq.Enumerable.OrderByDescending()
类似的东西:
(from qu in _que.OrderByDescending(u => u.RowKey).GetAll(
u => u.PartitionKey == partitionKey )
答案 5 :(得分:0)
尝试在System.Linq命名空间中使用OrderBy扩展方法:
http://msdn.microsoft.com/en-us/library/bb549264.aspx
此方法允许您有条件地为查询添加排序。
var _rowData = (from qu in _que.GetAll(
u => u.PartitionKey == partitionKey )
select new {
qu.PartitionKey,
qu.RowKey,
qu.Style,
qu.ShortTitle,
ModifiedToString = String.Format("{0:MM/dd/yyyy HH:mm}", qu.Modified)
});
// Let's say the user has selected they want to sort by RowKey
// and ModifiedToString, but not ShortTitle.
bool sortByRowKey = true;
bool sortByModifiedToString = true;
bool sortByShortTitle = false;
var query = _rowData.AsQueryable();
if(sortByRowKey) {
query = query.OrderBy(x => x.RowKey);
}
if(sortByModifiedToString) {
query = query.OrderBy(x => x.ModifiedToString);
}
if(sortByShortTitle) {
query = query.OrderBy(x => x.ShortTitle);
}
// Now let's call ToList() to execute the query and get the ordered data.
var _orderedData = query.ToList();