问题描述
我有名单,其中,SomeData>数据;
public class SomeData
{
public int Key { get; set;}
public decimal Value { get; set;}
}
另外,我有名单,其中,INT> DataOrder;
我要排序名单,其中,SomeData>数据
按键
,将其放置在相同的顺序名单,其中,INT> DataOrder
值。
I need to sort List<SomeData>data
by Key
, placing it in same order as List<int> DataOrder
values.
是否有任何常见的算法?
Is there any common algorithms for that?
例如:
List<SomeData> data = new List<SomeData>();
data.Add(new SomeData{ Key = 10, Value = 14 })
data.Add(new SomeData{ Key = 25, Value = 22 })
data.Add(new SomeData{ Key = 567, Value = 3 })
data.Add(new SomeData{ Key = 57, Value = 300 })
data.Add(new SomeData{ Key = 17, Value = 200 })
data.Add(new SomeData{ Key = 343, Value = 42 })
List<int> DataOrder = new List<int>{1, 25, 700, 567, 343, 350, 10};
排序后的结果:
Result after sorting:
foreach(var element in data)
{
Console.WriteLine(element.Key);
}
日期:
25
567
343
10
57
17
修改:初始数据
阵列可以有键
,那不是在包含 DataOrder
这样的值应放置在结果集合的任何顺序的末尾。例如改变来说明吧。
Edit: initial data
array can have Key
, that not contain in DataOrder
Such value should be placed at the end of result collection in any order.Example changed to illustrate it.
推荐答案
怎么样加盟:
var mySortedList = (from i in DataOrder
join d in data on i equals d.Key
select new SomeData
{
Key = d.Key,
Value = d.Value
});
编辑:为了还从数据添加这些值
不共享在 DataOrder
任意键-list您可以简单地添加一个联盟
的结果如下:
To also add those values from data
that do NOT share any key within the DataOrder
-list you may simply add a Union
to the result as follows:
var result = mySortedList.Union(data.Where(x => !DataOrder.Contains(x.Key)));
这篇关于分类收集另一个收藏价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!