Reputation: 773
I have a List containing a string property and another List. How can I in a datagrid display both the string property AND the properties from the containing List?
public class Main
{
public string Name { get; set; }
public List<Info> Info { get; set; }
}
public class Info
{
public string Info1 { get; set; }
public string Info2 { get; set; }
}
I would like my datagrid to show something like this:
#Name #Info1 #Info2
name info1 info2
name info1 info2
Thank you very much in advance.
Upvotes: 0
Views: 185
Reputation: 460340
The static way if you can change the Main
class is to provide string
-properties of the properties in the other class that you want to expose:
public class Main
{
public string Name { get; set; }
public List<Info> Info { get; set; }
public string Info1 {
get {
return Info == null || Info.Count == 0 ? ""
: Info.Last().Info1;
}
}
public string Info2
{
get
{
return Info == null || Info.Count == 0 ? ""
: Info.Last().Info2;
}
}
}
Other approaches:
you could use an anonymous type:
this.dataGridView1.DataSource = mains
.Select(m => new {
m.Name,
Info1 = m.Info.Last().Info1,
Info2 = m.Info.Last().Info2, // add null or count=0 check here
}).ToList();
Upvotes: 2
Reputation: 46997
If you want to take the last record from the Info list for each Main item you can write:
var q = from m in mainList
let i = m.Info.LastOrDefault()
select new
{
m.Name,
Info1 = i == null ? null : i.Info1,
Info2 = i == null ? null : i.Info2,
};
Upvotes: 1