我看到了大量关于OrderBy()、.ThenBy()、Sort()、IComparable以及诸如此类的文章。不过,我无法正确地对我的清单进行排序。
我需要根据结果(字符串)对食谱列表a进行排序,如果菜谱是可制作的。这将使可制作食谱在按字母顺序排序的列表中居首位,而下面的非手工艺食谱也会按字母顺序排序(结果是一个字符串,项目的名称)。就像这样:
在此之前:
之后
这样才能保证我的球员能得到最好的结果。这大致是菜谱类的样子:
public class Recipe : ScriptableObject
{
public Ingredient[] ingredients;
public string result;
public bool Craftable => //Not so complex and boring logic here;
}以下是我目前正在尝试的方法:
Recipe[] recipes = _recipes.OrderBy(r => r.Craftable).ThenBy(r => r.result).ToArray();这分类了a,但它不能区分手工艺和非工匠。
我很高兴知道是否已经有一个问题有答案,这是否是一个重复。
而且,我知道,我可以通过在两个不同的数组中将可制作的Recipe和不可手工的Recipe分开,然后分别对它们进行a排序,但这将是很无聊的。我想要更好更有趣的东西。
我很想知道哪一种是最有表现力的,因为我一秒钟就能处理数百万的食谱。
提前感谢您的帮助。
发布于 2018-11-17 14:10:27
你为什么就不能这样做?
var res = recipes.OrderBy(r => !r.Craftable).ThenBy(x => x.result);更新:
我测试了我的解决方案。看起来一切都很好:
var recipes = new List<Recipe>
{
new Recipe { result = "arrow", Craftable = true},
new Recipe { result = "boat", Craftable = false},
new Recipe { result = "apple", Craftable = false},
new Recipe { result = "can", Craftable = true},
new Recipe { result = "box", Craftable = true}
};
var res = recipes.OrderBy(r => !r.Craftable).ThenBy(x => x.result);
// note !r.Craftable in OrderBy clause, it means we first take craftable您还可以让它按以下方式工作。它输出同样的结果:
var res = recipes.OrderByDescending(r => r.Craftable).ThenBy(x => x.result);
// false = 0, true = 1, so we sort Craftable by descending, first 1 (Craftable = true), then 0 (Craftable = false)这给了我以下结果:
https://stackoverflow.com/questions/53351889
复制相似问题