C# 如何从linq select查询初始化字符串列表?
我正在初始化下面代码中的字符串列表:C# 如何从linq select查询初始化字符串列表?,c#,linq,C#,Linq,我正在初始化下面代码中的字符串列表: var headerValues = new Dictionary<string, List<string>> { { "section1", new List<string>() {
var headerValues = new Dictionary<string, List<string>>
{
{
"section1",
new List<string>()
{
"id",
"item"
}
},
{
"section2",
new List<string>()
{
"titile",
"content1",
"content2"
}
},
// and the rest of sections
};
var results = from s1 in section1Collection
from s2 in section2Collection
from s3 in section3Collection
from s4 in section4Collection
select new List<string>
{
// section1
GetValue(s1, headerValues["section1"][0]),
GetValue(s1, headerValues["section1"][1]),
// section2
GetValue(s2, headerValues["section2"][0]),
GetValue(s2, headerValues["section2"][1]),
GetValue(s2, headerValues["section2"][2]),
// and the rest of sections
};
但一定有一个循环的方法,对吗?或者在函数中初始化结果列表
如何以更智能、更可靠和更可读的方式生成此结果列表
顺便说一句,GetValue方法只是从传入的头值字符串中查找s1、s2等中的值
编辑:我要找的是这样的东西:
var results = from s1 in section1
from s2 in section2
from s3 in section3
from s4 in section4
select new List<string>
{
// GetValues should return all section1 strings based on the headerValues["section1"] array
GetValues(s1, headerValues["section1"]),
// section2
GetValues(s2, headerValues["section2"]),
// and the rest of sections
};
如前所述,您正在寻找的是SelectMany。它将嵌套集合展平为一维集合。下面是你应该如何使用它
var results = headerValues.SelectMany(item => item.Value);
那它是干什么的?”item'这里是一个KeyValuePairsince字典,您使用的字典由它们组成,item.Value是一个列表,因为它是此特定字典值的类型。现在,给定列表列表,SelectMany将它们合并并作为单个IEnumerable字符串返回您可以使用SelectMany,它将展平每个子列表。除了你说你想要一个字符串列表之外,不确定你到底在问什么,但是你有一个字符串列表。。。没什么,这不会编译。。。即使可以,它也将是一个具有属性的对象列表,您需要更好地解释您的输出