Wasn’t sure how to write a good title for this question… 🙂
I’m new to Linq and not sure what syntax to use for this problem I have
class MainClass()
{
string MainKey {get;set;}
string MainName {get;set;}
List<SmallObject> MainList {get;set}
}
class SmallObject()
{
string SmallKey {get;set}
}
Linq:
myTable contains of 4 string fields (Field1, Field2, Field3, Field4)
var mainQuery = (from v from myTable
select v)
var myQuery = (from v in mainQuery
select new MainClass()
{
MainKey = v.Field1,
MainName = v.Field2,
MainList = #whats the correct syntax here?#
})
The part marked with #whats the correct syntax here?# is my problem.
I want to add v.Field3 and v.Field4 as items to the MainList-object in MainClass, but I don’t know how to do that.
I’m happy if anyone can help.
You can create a
List<T>(or any other collection) and add items to it with a collection initializer:Update:
Since
Field3andField4are strings, you would just do what you already do to make them intoSmallObjects:Or, you could add a
SmallObjectconstructor that takes a string argument and use it likenew SmallObject(v.Field3).