0

I have a class that I made and I want to use it for a list but when I try adding data to it and loop through the list all I'm getting is the address of the class. I have no idea why its added that as the values.

My Class is

public class Regions
{
    public int dataID { get; set; }
    public int documentID { get; set; }
    public string region_ID { get; set; }
    public string region_Name { get; set; }
    public string sortID { get; set; }
}

This is how I am trying to add the values. The query has the right data in it, but the list isn't getting the data, just where the class resides.

List<Regions> lst = new List<Regions>();

var q = dt.AsEnumerable()
.Select(region => new {
    dataID = region.Field<int>("dataID"),
    documentID = region.Field<int>("documentID"),
    region_ID = region.Field<string>("Region_ID"),
    region_Name = region.Field<string>("Region_Name"),
    sortID = region.Field<string>("SortID").ToString()
});

foreach (var d in q)
lst.Add(new Regions() { dataID = d.dataID, 
    documentID = d.documentID, 
    region_ID = d.region_ID, 
    region_Name = d.region_Name, 
    sortID = d.sortID 
});

Query Results

List Data

EDIT Here is a link that I found that is similar what I am trying to do, but it doesn't seem he had the same errors as I did. I tried that answer, but wasn't working for me. Storing data into list with class

Fixed When I was looping through the list, I wasn't reading it properly.

Community
  • 1
  • 1
Chris
  • 2,953
  • 10
  • 48
  • 118
  • Are you talking about what you see in the debugger? If so, simply click the plus sign next to the class and you'll see the internal property data. – Yuval Itzchakov Nov 28 '14 at 23:04
  • How do you get this result? I guess, that if you override ToString() method you will get the expect text result. However, I think that your list already contains expected result. – empi Nov 28 '14 at 23:04
  • @YuvalItzchakov, its not what I see in the bugger. its what I see when I run it. I attached pics to show that the query is populated, and the 2nd pic is the results from the list. – Chris Nov 28 '14 at 23:10
  • @empi, The query is based off of a datatable that I have. I tried using .ToString when adding the values to the list, but still get the same results as shown in the pics. – Chris Nov 28 '14 at 23:11

2 Answers2

1

Try adding this in Regions

public override string ToString()
{
    return region_Name;
}
trashr0x
  • 6,457
  • 2
  • 29
  • 39
1

actually you can create the list in one step

List<Regions> lst = dt.Rows.OfType<DataRow>().Select(region => new Regions{
  dataID = region.Field<int>("dataID"),
  documentID = region.Field<int>("documentID"),
  region_ID = region.Field<string>("Region_ID"),
  region_Name = region.Field<string>("Region_Name"),
  sortID = region.Field<string>("SortID")
}).ToList();