c# - 如何在 C# 中的多列 ListView 中导入学生列表?
问题描述
我想将 Student、DOB、Location 的列表导入 ListView1
我的代码导致“Nil”值,一直试图修复几个小时但没有运气
任何帮助是极大的赞赏。
List<Student> students = new List<Student>() {
new Student() { name = "AAA", dob = DateTime.ParseExact("10-05-2000", "dd-MM-yyyy", CultureInfo.InvariantCulture), location = "Mumbai"},
new Student() { name = "BBB", dob = DateTime.ParseExact("05-02-2000", "dd-MM-yyyy", CultureInfo.InvariantCulture), location = "Pune"},
new Student() { name = "CCC", dob = DateTime.ParseExact("01-01-2000", "dd-MM-yyyy", CultureInfo.InvariantCulture), location = "Delhi"},
new Student() { name = "DDD", dob = DateTime.ParseExact("20-03-1999", "dd-MM-yyyy", CultureInfo.InvariantCulture), location = "Lucknow"},
new Student() { name = "EEE", dob = DateTime.ParseExact("15-06-1999", "dd-MM-yyyy", CultureInfo.InvariantCulture), location = "Chennai"},
new Student() { name = "FFF", dob = DateTime.ParseExact("18-09-1999", "dd-MM-yyyy", CultureInfo.InvariantCulture), location = "Ahmedabad"}
};
var results = students.OrderByDescending(x => x.dob) //sort from youngest to oldest
.GroupBy(x => x.dob.Year) //group by year
.Select(x => x.First()) //get first student born each year which is youngest
.ToList();
listView1.Items.Clear();
int counterOfArraylist = results.Count;
string[] str = new string[counterOfArraylist];
for (int i = 0; i < str.Length; i++) { str[i] = results[i].ToString(); }
listView1.Items.Add(new ListViewItem(str));
}
}
public class Student
{
public DateTime dob { get; set; }
public string name { get; set; }
public string location { get; set; }
}
解决方案
为了results[i].ToString();
按预期工作,您应该重写ToString()
类的方法并返回您喜欢的值:
public class Student
{
public DateTime dob { get; set; }
public string name { get; set; }
public string location { get; set; }
public override string ToString()
{
return name + " - " + dob.ToString("MMM dd, yyyy")+ " - " +location;
}
}
或者只是将其内联添加到您的代码中:
for (int i = 0; i < str.Length; i++) { str[i] = return name + " - " + dob.ToString("MMM dd, yyyy")+ " - " +location; }
如果您希望将每个属性放在单独的列中,那么您可以简单地执行以下操作:
ListViewItem[] items = results
.Select(x => new ListViewItem(new string[]{x.name, x.dob.ToString("MMM dd, yyyy"), x.location})
.ToArray();
listView1.Items.AddRange(items);
推荐阅读
- c# - 获取复选框 Item Asp.net core 的 Id
- python - Find/replace in VS Code Jupyter Notebooks
- python - 如果我向 simpleSAMLphp(作为 IDP)发送 Authnrequest,将其发送到的正确 URL 是什么?
- javascript - JS中函数内的变量赋值
- css - 使用 WebStorm 查找重复的 CSS 类
- java - PDF 中的条形码未在 FireFox 中显示
- c# - 元素 Auto Grid.Row 和 Grid.Column
- php - 通过 Angular 的 POST-Request 发送时未设置 PHP Cookie
- c++ - SDL2 Window 使用固定且不可更改的值进行初始化
- sql - R中的sql查询,比较两个日期