Reputation: 9080
I'm expounding on this question: Create object from LINQ
I've had to change the contactsList from a List to a List which will contain the Name and Id.
public class DataItem
{
public String Location { get; set; }
public List<ContactInfo> ContactsList { get; set; }
}
public class ContactInfo
{
public String PersonName { get; set; }
public Int32 PersonId { get; set; }
}
var myData= from table in sqlResults.AsEnumerable()
group table by table["LOCATION"] into groupby
select new DataItem
{
Location = groupby.Key.ToString(),
ContactsList = groupby.Select(row => new ContactInfo
{
PersonName = row["PERSON"].ToString(),
PersonId = (Int32)row["PERSONID"]
}).ToList()
};
//TreeView
tv.DataContext = BrokerData;
I'm getting a Specified Cast is Invalid
What am I doing incorrectly here?
UPDATE
I'm getting an highlighted error here:
new ContactInfo
{
PersonName = row["PERSON"].ToString(),
PerrsonId = (Int32)row["PERSONID"]
}).
Upvotes: 0
Views: 192
Reputation: 152501
Instead of the weakly typed indexer
PersonId = (Int32)row["PERSONID"]
use the strongly-typed Field
extension method
PersonId = row.Field<Int32>("PERSONID")
If PERSONID
can be null and you want to store null
in that case, make PersonId nullable:
public Int32? PersonId { get; set; }
and
PersonId = row.Field<Int32?>("PERSONID")
Upvotes: 2