从JSON加载的数组中对字段进行排序的最简单方法是什么。我在匿名函数中找到了一些东西,但我想知道这是否是一种更基本的方法。
static void SortItems(Items[] items)
{
Console.WriteLine("Choose field to sort (Name, Weapon, Strength)");
string userInput = Console.ReadLine();
Items[] sortedItem;
if (userInput.ToLower() == "name")
{
string[] name = items.Select( m => m.Name).ToArray();
}
else if (userInput.ToLower() == "weapon")
{
string[] weapon = items.Select(m => m.EquippedWeapon.Name).ToArray();
}
else if (userInput.ToLower() == "strength")
{
int[] totalStrength = items.Select(m => m.GetStrength()).ToArray();
}
sortedItems = Sorts.Sort(items, userInput);
foreach (Items c in sortedItems)
{
Console.WriteLine("Name : {0} - Weapon: {1} - Total strength: {2}", c.Name, c.Weapon.Name, c.strength().ToString());
}
}
答案 0 :(得分:0)
如果你能够使用Linq扩展,你可以做更像这样的事情
static void SortItems(Items[] items)
{
Console.WriteLine("Choose field to sort (Name, Weapon, Strength)");
string userInput = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(userInput))
{
Items[] sortedItems;
switch (userInput.Trim().ToLower())
{
case ("name"):
sortedItems = items.OrderBy(x => x.Name).ToArray();
break;
case ("weapon"):
sortedItems = items.OrderBy(x => x.Weapon).ToArray();
break;
case ("strength"):
sortedItems = items.OrderBy(x => x.Strength).ToArray();
break;
default:
//return whatever for default
sortedItems = items.OrderBy(x => x.Name).ToArray();
break;
}
foreach (Items c in sortedItems)
{
Console.WriteLine("Name : {0} - Weapon: {1} - Total strength: {2}", c.Name, c.Weapon.Name,
c.strength().ToString());
}
}