我有以下代码:
public class Info
{
public string Name;
public string Num;
}
string s1 = "a,b";
string s2 = "1,2";
IEnumerable<Info> InfoSrc =
from name in s1.Split(',')
from num in s2.Split(',')
select new Info()
{
Name = name,
Num = num
};
List<Info> listSrc = InfoSrc.ToList();
我希望我的
listSrc
结果包含两个Info
项,它们的Name
和Num
属性是:a, 1
b, 2
但是,上面显示的代码有四个结果:
a, 1
a, 2
b, 1
b, 2
最佳答案
您可以使用Enumerable.Zip
:
IEnumerable<Info> InfoSrc = s1.Split(',')
.Zip(s2.Split(','), (name, num) => new Info(){ Name = name, Num = num });
如果需要将两个以上的集合映射到属性,可以将多个
Zip
与包含第二个和第三个的匿名类型链接在一起:IEnumerable<Info> InfoSrc = s1.Split(',')
.Zip(s2.Split(',').Zip(s3.Split(','), (second, third) => new { second, third }),
(first, x) => new Info { Name = first, Num = x.second, Prop3 = x.third });
下面是一个更具可读性的版本:
var arrays = new List<string[]> { s1.Split(','), s2.Split(','), s3.Split(',') };
int minLength = arrays.Min(arr => arr.Length); // to be safe, same behaviour as Zip
IEnumerable<Info> InfoSrc = Enumerable.Range(0, minLength)
.Select(i => new Info
{
Name = arrays[0][i],
Num = arrays[1][i],
Prop3 = arrays[2][i]
});