如何从两个值创建列表? [英] How to create a list from two values?
问题描述
不确定如何为这个问题写一个好标题...:)
Wasn't sure how to write a good title for this question... :)
我是Linq的新手,不确定要使用什么语法解决这个问题
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包含4个字符串字段(Field1,Field2,Field3,Field4)
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?#
})
标有#的语法在这里是什么?#是我的问题. 我想将v.Field3和v.Field4作为项目添加到MainClass的MainList对象中,但是我不知道该怎么做.
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:
MainList = new List<SmallObject> { v.Field3, v.Field4 }
更新:
由于Field3
和Field4
是字符串,因此您只需做已经做的事情就可以将它们变成SmallObject
s:
Since Field3
and Field4
are strings, you would just do what you already do to make them into SmallObject
s:
MainList = new List<SmallObject>
{
new SmallObject { SmallKey = v.Field3 },
new SmallObject { SmallKey = v.Field4 },
}
或者,您可以添加一个带有字符串参数的SmallObject
构造函数,并像new SmallObject(v.Field3)
一样使用它.
Or, you could add a SmallObject
constructor that takes a string argument and use it like new SmallObject(v.Field3)
.
这篇关于如何从两个值创建列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!