如何在C#中的多列ListView中导入学生列表?

时间:2019-03-23 12:06:17

标签: c# listview

我想将Student,DOB,位置列表导入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; }
}

1 个答案:

答案 0 :(得分:0)

为了使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);