[英]Linq for sorting C#
天氣很熱,所以我的大腦不能很好地工作。 什么是使用LINQ對此進行排序的最佳方法? 請注意,排序基於“C”進行,但適用於“M”
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Compare
{
public class M
{
public IList<C> Columns = new List<C>();
}
public class C
{
public bool SortByMe { get; set; }
public string Guid { get; set; }
}
class Program
{
static void Main(string[] args)
{
IList<M> list = new List<M>();
M one = new M();
one.Columns.Add(new C()
{
SortByMe = true,
Guid = "5"
});
one.Columns.Add(new C()
{
});
one.Columns.Add(new C()
{
});
M two = new M();
two.Columns.Add(new C()
{
});
two.Columns.Add(new C()
{
SortByMe = true,
Guid = "2"
});
two.Columns.Add(new C()
{
});
M three = new M();
three.Columns.Add(new C()
{
});
three.Columns.Add(new C()
{
SortByMe = true,
Guid = "100"
});
three.Columns.Add(new C()
{
});
list.Add(one);
list.Add(two);
list.Add(three);
//Then sort the M by the occurrence of a C with SortByMe true.
}
}
}
您的意思是每個M
實例在其Columns
集合中具有單個 C
實例,其SortByMe
屬性為true
; 並且您希望通過這些C
元素的GUID
值對M
實例的集合進行排序?
list = list.OrderBy(m => m.Columns.Single(c => c.SortByMe).Guid).ToList();
請注意,由於GUID
是string
,因此您的排序將按字母順序排列( "100"
, "2"
, "5"
),而不是數字。 如果你想要它是數字,你需要拋出一個int.Parse
。
編輯 :執行數字排序的版本:
list = list.OrderBy(m => int.Parse(m.Columns.Single(c => c.SortByMe).Guid)).ToList();
和邏輯等效的查詢語法:
list =
(
from m in list
orderby
(
from c in m.Columns
where c.SortByMe
select int.Parse(c.Guid)
).Single()
select m
).ToList();
您需要考慮到原始假設的任何失敗 - 例如給定Columns
集合中的多個C
元素將其SortByMe
設置為true
,或者GUID
值不是有效整數 - 將導致整個表達式失敗。
var query = from m in list
let c = m.First(x => x.SortByMe)
orderby c.Guid
select m;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.