将多个字符串拆分为 C# 中的对象列表

Split multiple strings into a list of objects in C#

我有以下代码:

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 项目,其 NameNum 属性是:

a, 1
b, 2

但是,我上面显示的代码产生了四个项目:

a, 1
a, 2
b, 1
b, 2

假设每个列表中的项目数量相等,看起来您正试图 Zip 将它们放在一起...

s1.Split(',').Zip(s2.Split(','), (name, num) => new Info{Name = name, Num = num})

您可以使用 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]
 });