关于排序
我在这里看到的一个问题是,您的第二个“字符串”实际上不是字符串,而是数字。因此,您实际上有一个有名字和年龄的人。
为什么这很重要?
排序取决于数据的类型。字符串按字母顺序排序,而数字按数字排序。
考虑以下列表:
1, 2, 17, 11, 100, 20, 34
这可以通过多种方式排序
Numerical Alphabetical
--------- ------------
1 1
2 100
11 11
17 17
20 2
34 20
100 34
鉴于您很可能希望按数字排序,您需要将数据存储为int,而不是string。
如何存储数据?
这取决于您的用例。如果保证名称是唯一的,那么您可以使用Dictionary<string,int>。否则,我建议您创建一个类 Person 并使用 ICollection<Person> 来存储它们。
作为Dictionary<string, int>
如果可以保证名称在您的域中是唯一的,则此方法很有用。此外,它只使用内置类型。
namespace DictionaryTest
{
public class Program
{
public static void Main(string[] args)
{
//Create a dictionary to store people
Dictionary<string, int> people = new Dictionary<string, int>();
//Add some people. Note that this is type-safe
people.Add("John", 23);
people.Add("Doe", 12);
people.Add("Maria", 41);
//people.Add("John", 55); // <-- This will fail because there is already a John
//Create queries to ensure correct sorting
var peopleByName = from p in people
orderby p.Key //Our name is the key, the age is the value
select new {Name = p.Key, Age = p.Value};
var peopleByAge = from p in people
orderby p.Value
select new {Name = p.Key, Age = p.Value};
var peopleByAgeDescending = from p in people
orderby p.Value descending
select new {Name = p.Key, Age = p.Value};
//Execute the query and print results
foreach(var person in peopleByAge)
{
Console.WriteLine("Hello, my name is {0} and I am {1} years old", person.Name, person.Age);
}
}
}
}
Try it online!
作为ICollection<Person>
这种方法定义了一个类Person,它只包含一个Name 和一个Age 属性,但可以扩展为包含更多信息、方法等。
namespace ClassTest
{
public class Program
{
public static void Main(string[] args)
{
//Create a list to store people
ICollection<Person> people = new List<Person>();
//Add some people. Note that this is type-safe
people.Add(new Person(){ Name = "John", Age = 23, FavouriteColour = "Blue" });
people.Add(new Person(){ Name = "Doe", Age = 12});
people.Add(new Person(){ Name = "Maria", Age = 41, FavouriteColour = "Purple" });
people.Add(new Person(){ Name = "John", Age = 55, FavouriteColour = "Gray" }); //<-- You can indeed have two people with the same name
//Create queries to ensure correct sorting
var peopleByName = from p in people
orderby p.Name
select p;
var peopleByAge = from p in people
orderby p.Age
select p;
var peopleByAgeDescending = from p in people
orderby p.Age descending
select p;
//Execute the query and print results
foreach(var person in peopleByAge)
{
Console.WriteLine("Hello, my name is {0} and I am {1} years old.", person.Name, person.Age);
if(person.FavouriteColour != null)
{
Console.WriteLine("My favourite colour is {0}.", person.FavouriteColour);
}
else
{
Console.WriteLine("I have no favourite colour.");
}
Console.WriteLine(); //Add a new line for better readability
}
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string FavouriteColour { get; set; }
}
}
Try it online!
我个人更喜欢第二种方法,因为它更具可扩展性,并且不需要名称的唯一性。它允许您随心所欲地扩展Person 类,并为您提供更多排序选项。