我得到了一个包含三个不同实例变量的类Person
。
我还有一个列表persons
,其中包含一些Person
个对象。
如何创建一个新的列表,向我展示(比如树视图)生日,其中包含所有注册名称。
10/04/1950> Richard> Dan> John
18/16/1940> Jane>罗恩
.....
答案 0 :(得分:4)
您可以尝试这样的事情:
var list = persons.GroupBy(person=>person.BirthDate)
.Select(gr=> new
{
Day = gr.Key,
Names = string.Concat(",",gr.Select(x=>x.Name))
}).ToList();
这将创建一个对象列表,其中包含两个属性,一个是Date,另一个是逗号分隔的具有相同生日的人员名称列表。
答案 1 :(得分:0)
如果您希望将名称作为名称列表,请尝试以下操作:
var dateTree = (from p in persons
group p by p.BirthDate into g
select new
{
BirthDate = g.Key,
Names = persons.Where(x => x.BirthDate == g.Key).Select(y => y.Name)
}).ToList();
答案 2 :(得分:0)
我将结果放入字典中,然后显示在DataGridView中。见下面的代码
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
List<Person> people = new List<Person>() {
new Person() { BirthDate = DateTime.Parse("10/04/1950"), ID = 1, Name = "Richard"},
new Person() { BirthDate = DateTime.Parse("10/04/1950"), ID = 2, Name = "Dan"},
new Person() { BirthDate = DateTime.Parse("10/04/1950"), ID = 3, Name = "John"},
new Person() { BirthDate = DateTime.Parse("12/16/1950"), ID = 4, Name = "Jane"},
new Person() { BirthDate = DateTime.Parse("12/16/1940"), ID = 5, Name = "Ron"}
};
Dictionary<DateTime, List<Person>> dict = people.AsEnumerable()
.GroupBy(x => x.BirthDate, y => y)
.ToDictionary(x => x.Key, y => y.ToList());
DataTable dt = new DataTable();
dt.Columns.Add("BirthDate", typeof(DateTime));
dt.Columns.Add("Name", typeof(string));
foreach (Person person in dict[DateTime.Parse("10/04/1950")])
{
dt.Rows.Add(new object[] { person.BirthDate, person.Name });
}
dataGridView1.DataSource = dt;
}
}
public class Person
{
public int ID { get;set;}
public string Name { get;set;}
public DateTime BirthDate { get;set;}
}
}