C#多条数据按照字段A(int)大小进行排序
时间: 2024-03-18 21:40:04 浏览: 21
你可以使用 LINQ 进行多条数据按照字段 A(int)大小进行排序,示例代码如下:
```csharp
List<YourModel> models = new List<YourModel>();
// 添加数据到 models 中
var sortedModels = models.OrderBy(m => m.A);
```
其中,`YourModel` 是你的数据模型,`models` 是你要排序的数据列表,`A` 是你要按照其大小进行排序的字段。上述示例中,使用 `OrderBy` 方法对 `models` 列表进行排序,排序后的结果存储在 `sortedModels` 中,按照 `A` 字段从小到大排序。
相关问题
C# Sort获取某个字段进行排序
你可以使用 `OrderBy` 和 `ThenBy` 方法来按照指定的字段进行排序,例如:
```csharp
// 定义一个类用于排序
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
// 定义一个列表用于排序
List<Person> people = new List<Person>()
{
new Person() { Name = "Tom", Age = 20 },
new Person() { Name = "Alice", Age = 25 },
new Person() { Name = "Bob", Age = 20 },
};
// 按照 Age 字段进行排序,如果 Age 相同则按照 Name 字段排序
var sortedPeople = people.OrderBy(p => p.Age).ThenBy(p => p.Name);
// 输出排序结果
foreach (var person in sortedPeople)
{
Console.WriteLine(person.Name + " " + person.Age);
}
```
上述代码中,我们定义了一个 `Person` 类作为排序的对象,包含了 `Name` 和 `Age` 两个字段。接着定义了一个 `List<Person>` 类型的列表用于排序。我们使用 `OrderBy` 和 `ThenBy` 方法来按照 Age 和 Name 字段进行排序,最后输出排序结果。
C# 获取某个字段进行排序
如果您是想在C#中对某个字段进行排序,您可以使用LINQ(语言集成查询)来实现。以下是一个示例,假设您有一个名为“Person”的类,其中有一个名为“Age”的整数字段,您希望按照这个字段进行排序:
```csharp
List<Person> people = new List<Person>();
// 添加一些人物到列表中
people.Add(new Person("John", 25));
people.Add(new Person("Jane", 30));
people.Add(new Person("Bob", 20));
// 使用 LINQ 对年龄进行升序排列
var sortedPeople = people.OrderBy(p => p.Age);
// 输出排序后的结果
foreach (var person in sortedPeople)
{
Console.WriteLine(person.Name + " - " + person.Age);
}
```
上面的代码将按照年龄升序排列人物,并输出排序后的结果。请注意,您需要使用 `OrderBy` 方法,其中的 `p => p.Age` 表示按照 `Age` 字段进行排序。如果您想按照降序排列,可以使用 `OrderByDescending` 方法。