简体   繁体   English

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

[英]Split multiple strings into a list of objects in C#

I have the following code: 我有以下代码:

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();

I would like my listSrc result to contain two Info items whose Name and Num properties are: 我希望我的listSrc结果包含两个InfoName ,其NameNum属性是:

a, 1
b, 2

However, the code I show above results in four items: 但是,我上面显示的代码导致了四个项目:

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

You can use Enumerable.Zip : 你可以使用Enumerable.Zip

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

If you need to map more than two collections to properties you could chain multiple Zip together with an anonymous type holding the second and third: 如果您需要将两个以上的集合映射到属性,您可以将多个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 });

Here is a hopefully more readable version: 这是一个希望更具可读性的版本:

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]
 });

假设项目在每个列表的数量是相等的,它看起来像你试图邮编在一起......

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM