-1

I am trying to load my custom object with Data coming from Data Reader..How can I accomplish that

I can change the datareader to DATATable if it is better to use it

Reader Data

ID     Description Type
1      Test1       1
2      Test2       2
3      Test3       1
4      Test4       3  
5      Test5       3

my final Object should look something like this

type: 1
    id:1
    desc:Test1  
    id:3
    desc:Test3


type: 2
    id:2
    desc:Test2


type: 3
    id:4
    desc:Test4  
    id:5
    desc:Test5

Interface

public class Val
{
    public string type { get; set; }
    public List<valItems> valItems{ get; set; }
}

public class valItems
{

    public string id { get; set; }

    public string desc { get; set; }
}

function ( I am stuck here) it needs to b grouped by type see above final result)

ReadData()
{
//some code

       if (reader.HasRows)
            {

                while(reader.Read())
                {
                    dropdown.Add(new Dropdown
                    {
                        Type = Convert.ToString(reader["type"]),
                        valItems= 
                        }),
                    });
                }
            }



}
rgoal
  • 1,236
  • 11
  • 35
  • 61

2 Answers2

1

Not tested, but you can try grouping with something similar :

List<Val> result = reader.Cast<IDataRecord>().GroupBy(r => r["type"]?.ToString(), 
        r => new valItems { id = r["ID"]?.ToString(), 
                            desc = r["Description"]?.ToString() })
    .Select(g => new Val { type = g.Key, valItems = g.ToList()).ToList();
Slai
  • 22,144
  • 5
  • 45
  • 53
0

You can create a variable Dictionary<string, Val> types which holds for each type its Val object. Then as you read your data, you can add them to the valItems list of their type as follows.

types[Convert.ToString(reader["type"])].valItems.Add(new ValItems() {id = ..., desc = ...});

Of course, you have to handle the case where the dictionary entry needs to be created.

RobertBaron
  • 2,817
  • 1
  • 12
  • 19