[英]How to sort a list of objects by property using Bubble sort C#
I searched an answer for my question but I could not find anything. 我搜索了我的问题的答案,但找不到任何东西。 I am sorry if there is a similar theme. 很抱歉,如果有类似主题。 So I need to sort a list of objects by their property and I have to use bubble sort. 因此,我需要按照对象的属性对对象列表进行排序,并且必须使用气泡排序。 How can I make it without using methods like "list.sort". 不使用“ list.sort”之类的方法怎么做。 Thank you in advance! 先感谢您!
using System;
using System.Collections.Generic;
class Animals
{
public int id { get; set; }
public string name { get; set; }
public string color { get; set; }
public int age { get; set; }
}
class Program
{
static void Main()
{
Console.Write("How much animals you want to add?: ");
int count = int.Parse(Console.ReadLine());
var newAnimals = new List<Animals>(count);
Animals animal = new Animals();
newAnimals.Add(animal);
for (int i = 0; i < count; i++)
{
newAnimals[i].id = i;
Console.Write("Write name for animal: " + i + ": ");
newAnimals[i].name = Console.ReadLine();
Console.Write("Write age for animal: " + i + ": ");
newAnimals[i].age = int.Parse(Console.ReadLine());
Console.Write("Write color for animal: " + i + ": ");
newAnimals[i].color = Console.ReadLine();
newAnimals.Add(new Animals() { id = 1, name = "name" });
}
Console.WriteLine("Name \tAge \tColor");
for (int i = 0; i < count; i++)
{
Console.WriteLine(newAnimals[i].name + "\t" + newAnimals[i].age + "\t" + newAnimals[i].color);
}
Console.ReadLine();
}
}
Console.WriteLine("Name \tAge \tColor");
for (int i = 0; i < count; i++)
{
Console.WriteLine(newAnimals[i].name + "\t" + newAnimals[i].age + "\t" + newAnimals[i].color);
}
Console.ReadLine();
}
}
here you go (assuming that you want to sort by id) 到这里了(假设您想按ID排序)
for (int i = 0; i < newAnimals.Count; i++)
{
for (int j = 1; j <= i; j++)
{
if (newAnimals[j - 1].id > newAnimals[j].id)
{
Animals temp = newAnimals[j - 1];
newAnimals[j - 1] = newAnimals[j];
newAnimals[j] = temp;
}
}
}
Generic, with dynamic property selector : 通用,带有动态属性选择器:
public static class MyExtensions
{
public static void BubbleSort<T>(this List<T> list, Func<T, int> selector)
{
while (true)
{
bool changed = false;
for (int i = 1; i < list.Count; i++)
{
if (selector(list[i - 1]) > selector(list[i]))
{
T temp = list[i - 1];
list[i - 1] = list[i];
list[i] = temp;
changed = true;
}
}
if (!changed)
break;
}
}
}
Usage: 用法:
unsortedList.BubbleSort(x => x.SortProperty);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.