Get data from SQL into a list with sublists in C# - Stack Overflow

admin2025-04-18  2

In most cases, I use a simple observable collection in C# and fill it with data fetched from a SQL query.

Something like this works:

public class MyClass
{
    public string mystring1 { get; set; } = String.Empty;
    public string mystring1 { get; set; } = String.Empty;
}

ObservableCollection<MyClass> MyClassData = new ObservableCollection<MyClass>();

I can easily insert data fetched by SqlDataReader:

while (dataReader.Read())
{
    MyClassData.Add(new MyClass{ mystring1 = dataReader.GetValue(0).ToString(), mystring2 =  dataReader.GetValue(1).ToString() }});
}

As it turned out, I need a 3rd member in my class and it should be not a simple string but a list, so I wrote this:

public class MySubClass
{
    public string mystring3 { get; set; }
}

public class MyClass
{
    public string mystring1 { get; set; } = String.Empty;
    public string mystring1 { get; set; } = String.Empty;
    public List<MySubClass> MySubClassData { get; set; }
}

Even its only a simple string in MySubClass, I need this as list for later use.

And now I have the big problem to find the right syntax how to get the SQL data into the new structure and all I get is a bunch of curious errors while compiling.

I just don't know how to address the mystring3 in mySubClass as member of MyClass to store data in it.

Please give me a hint.

Thanks,

Hans

转载请注明原文地址:http://anycun.com/QandA/1744909016a89332.html