[英]C# Sort ListBox items using ComboBox
在这个程序中,我必须在一个目录中显示许多媒体文件(在模拟文本文件中创建),并允许用户选择 ComboBox 项目来过滤 ListBox 中显示的结果。 我设法让它按字母顺序排序,但我不知道如何按数字排序。
示例:CarShow、AVI、723MB、2019094(文件名、文件类型、文件大小、上次修改日期)
我想重新排序 ListBox 的其他 3 种方法是按文件类型、文件大小和上次修改日期。
我希望它跳过第一部分(文件名)并检查其他元素。 我该怎么做?
public partial class MainForm : Form
{
// Declare Lists for each of the following: audio, image, document, video
List<Audio> audioList = new List<Audio>();
List<Image> imageList = new List<Image>();
List<Document> documentList = new List<Document>();
List<Video> videoList = new List<Video>();
// Affiliate class with variable
Audio currentAudio = new Audio();
Image currentImage = new Image();
Document currentDocument = new Document();
Video currentVideo = new Video();
// Declare int variables as 0
int numAudio = 0;
int numImage = 0;
int numDocument = 0;
int numVideo = 0;
int numFiles = 0;
public MainForm()
{
InitializeComponent();
}
/// <summary>
///
/// </summary>
private void ReadFile()
{
try
{
StreamReader inputFile; //To read the file
string line; //To hold a line from the file
//Create a delimiter array
char[] delim = { ',' };
//Open the Files.txt file
inputFile = File.OpenText("Files.txt");
//Read the lines from the file
while (!inputFile.EndOfStream)
{
//Read a line from the file
line = inputFile.ReadLine();
//Tokenize the line
string[] tokens = line.Split(delim);
// Check if the first tokenized string contains "Audio"
if (tokens[0] == "Audio")
{
currentAudio = new Audio();
// Tokenized variables are numbered and parsed
currentAudio.Name = tokens[1];
currentAudio.Type = tokens[2];
currentAudio.Size = tokens[3];
currentAudio.LastModification = int.Parse(tokens[4]);
currentAudio.Artist = tokens[5];
currentAudio.BitRate = int.Parse(tokens[6]);
//Add one to the count of the amount of audio files
numAudio += 1;
// Add field to created list
audioList.Add(currentAudio);
// Send the following fields to the targeted ListBox
filesListBox.Items.Add(currentAudio.Name + ", " + currentAudio.Type + ", " + currentAudio.Size + ", " + currentAudio.LastModification);
}
// Check if the first tokenized string contains "Media"
else if (tokens[0] == "Media")
{
// Check if the first tokenized string contains "Video"
if (tokens[1] == "Video")
{
currentVideo = new Video();
// Tokenized variables are numbered and parsed
currentVideo.Name = tokens[2];
currentVideo.Type = tokens[3];
currentVideo.Size = tokens[4];
currentVideo.LastModification = int.Parse(tokens[5]);
currentVideo.Director = tokens[6];
currentVideo.Producer = tokens[7];
//Add one to the count of the amount of audio files
numVideo += 1;
// Add field to created list
videoList.Add(currentVideo);
// Send the following fields to the targeted ListBox
filesListBox.Items.Add(currentVideo.Name + ", " + currentVideo.Type + ", " + currentVideo.Size + ", " + currentVideo.LastModification);
}
// Check if the first tokenized string contains "Image"
else if (tokens[1] == "Image")
{
currentImage = new Image();
// Tokenized variables are numbered and parsed
currentImage.Name = tokens[2];
currentImage.Type = tokens[3];
currentImage.Size = tokens[4];
currentImage.LastModification = int.Parse(tokens[5]);
currentImage.Width = decimal.Parse(tokens[6]);
currentImage.Height = decimal.Parse(tokens[7]);
currentImage.Resolution = tokens[8];
//Add one to the count of the amount of audio files
numImage += 1;
// Add field to created list
imageList.Add(currentImage);
// Send the following fields to the targeted ListBox
filesListBox.Items.Add(currentImage.Name + ", " + currentImage.Type + ", " + currentImage.Size + ", " + currentImage.LastModification);
}
}
// Check if the first tokenized string contains "Document"
else if (tokens[0] == "Document")
{
currentDocument = new Document();
// Tokenized variables are numbered and parsed
currentDocument.Name = tokens[1];
currentDocument.Type = tokens[2];
currentDocument.Size = tokens[3];
currentDocument.LastModification = int.Parse(tokens[4]);
currentDocument.NumPages = int.Parse(tokens[5]);
currentDocument.NumWords = int.Parse(tokens[6]);
currentDocument.DocSubject = tokens[7];
//Add one to the count of the amount of audio files
numDocument += 1;
// Add field to created list
documentList.Add(currentDocument);
filesListBox.Items.Add(currentDocument.Name + ", " + currentDocument.Type + ", " + currentDocument.Size + ", " + currentDocument.LastModification);
}
}
// Close file
inputFile.Close();
}
catch (Exception ex)
{
//Display an error message
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
// Call method ReadFile when the form loads
ReadFile();
// Field numFiles is equivalent to its many attributes
numFiles = (numAudio + numImage + numDocument + numVideo);
// Declare TextBox location for the field numFiles
numberFilesTextBox.Text = numFiles.ToString();
// Add ListBox items for the following string and its field
numberFilesTypeListBox.Items.Add("Audio: " + numAudio);
numberFilesTypeListBox.Items.Add("Image: " + numImage);
numberFilesTypeListBox.Items.Add("Document: " + numDocument);
numberFilesTypeListBox.Items.Add("Video: " + numVideo);
}
private void ReorganizeComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
// if the ComboBox text selected is "File Name" then organize in alphabetical order
if (reorganizeComboBox.Text == "File Name")
{
// Organize in alphabetical order
filesListBox.Sorted = true;
}
else if (reorganizeComboBox.Text == "File Type")
{
}
else if (reorganizeComboBox.Text == "File Size")
{
}
else if (reorganizeComboBox.Text == "Last Modification Date")
{
}
}
}
如果有一个包含所有属性的类和一个用于排序选项的Enum
,最小示例:
类和枚举
class FileDescriptor
{
public string Name { get; set; }
public string Extension { get; set; }
public long Size { get; set; }
public DateTime LastModified { get; set; }
override public string ToString()
{
return $"{Name}, {Extension}, {Size}, {LastModified.ToString("yyyyMMd")}";
}
}
enum SortEnum
{
Name,
Extension,
Size,
LastModified
}
ComboBox
有一个SelectedIndexChanged
事件, ListBox
根据用户选择进行排序:
private void Form1_Load(object sender, EventArgs e)
{
// Mockup for testing
var files = new FileDescriptor[]
{
new FileDescriptor()
{
Name = "CarShow",
Extension = "AVI",
Size = 723,
LastModified = DateTime.ParseExact("2019094", "yyyyMMd", CultureInfo.InvariantCulture)
},
new FileDescriptor()
{
Name = "FoodMenu",
Extension = "PDF",
Size = 200,
LastModified = DateTime.ParseExact("20190214", "yyyyMMd", CultureInfo.InvariantCulture)
},
new FileDescriptor()
{
Name = "MathProblems",
Extension = "TXT",
Size = 13,
LastModified = DateTime.ParseExact("2018053", "yyyyMMd", CultureInfo.InvariantCulture)
}
};
var sortOptions = Enum.GetValues(typeof(SortEnum));
this.lb_FileDescriptions.DataSource = files;
this.cb_SortOptions.DataSource = sortOptions;
}
private void cb_SortOptions_SelectedIndexChanged(object sender, EventArgs e)
{
var sortOption = (SortEnum)cb_SortOptions.SelectedValue;
var files = lb_FileDescriptions.Items.Cast<FileDescriptor>();
switch (sortOption)
{
case SortEnum.Name:
lb_FileDescriptions.DataSource = files.OrderBy(f => f.Name)
.ToList();
break;
case SortEnum.Extension:
lb_FileDescriptions.DataSource = files.OrderBy(f => f.Extension)
.ToList();
break;
case SortEnum.Size:
lb_FileDescriptions.DataSource = files.OrderBy(f => f.Size)
.ToList();
break;
case SortEnum.LastModified:
lb_FileDescriptions.DataSource = files.OrderBy(f => f.LastModified)
.ToList();
break;
default:
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.