gpt4 book ai didi

c# - 按年份对自定义列表进行排序

转载 作者:太空宇宙 更新时间:2023-11-03 19:18:57 25 4
gpt4 key购买 nike

我最近一直在使用列表,但我似乎找不到在自定义类型列表中按年份排序的方法。在对我的列表进行排序时,我只是不知道如何定位年份信息。任何帮助将不胜感激。

我的代码可以在下面查看:

void Main()
{
List<DVD> myDVDList = GetFilms();
}

// Define other methods and classes here

public List<DVD> GetFilms()
{
var filmList = new List<DVD>();

string filename = @"C:\Users\****\Desktop\film-list.txt";
IEnumerable<string> rawList = File.ReadLines(filename);
int index = 1;

foreach(string line in rawList)
{
string[] filmInfo = line.Split('*');
var newDVD = new DVD(index, filmInfo[0], filmInfo[1], int.Parse(filmInfo[2]), filmInfo[3]);
filmList.Add(newDVD);

index++;
}

return filmList;
}

public class Product
{
public int IDNumber = 0;
public string Name = "";
public int Year = 0;

public Product(int idNumber, string name, int year)
{
IDNumber = idNumber;
Name = name;
Year = year;
}

public virtual void ProductInfo()
{
Console.WriteLine(string.Format("{0} - {1} - {2}", IDNumber,Name,Year));
}
}

public class DVD : Product
{
public string Director = "";
public string Genre = "";

public DVD(int idNumber, string name, string director, int year, string genre) : base(idNumber, name, year)
{
Director = director;
Genre = genre;
}

public override void ProductInfo()
{
Console.WriteLine(string.Format("[DVD - Product Information]: #{0} - {1} - {2} - {3} - {4}", IDNumber, Name, Director, Genre, Year));
}
}

最佳答案

在泛型上使用 LINQ List<Product>对象:

using System.Linq;
...
var orderedList = filmList.OrderBy(z => z.Year).ToList();

关于c# - 按年份对自定义列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13952681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com