简体   繁体   English

使用linq将逗号分隔的字符串转换为列表

[英]convert comma separated string to list using linq

I have 3 comma separated strings FirstName, MiddleInitial, LastName 我有3个逗号分隔的字符串FirstName, MiddleInitial, LastName

I have a class NameDetails : 我有一个NameDetails类:

public class NameDetails
{
    public string FirstName { get; set; }
    public string MiddleInitial { get; set; }
    public string LastName { get; set; }
}

I have the values for strings as: 我有字符串的值为:

FirstName ="John1, John2, John3"
MiddleInitial = "K1, K2, K3"
LastName = "Kenndey1, Kenndey2, Kenndey3"

I need to fill the NameDetails List with the values from the comma separated strings. 我需要用逗号分隔的字符串中的值填充NameDetails列表。

Any linq for this? 任何linq为此? I need this for my asp.net mvc (C#) application. 我需要这个用于我的asp.net mvc(C#)应用程序。

I don't neccesarily advocate this as a good solution but it does what you asked, which is to 'do it in LINQ'. 我不一定提倡这是一个很好的解决方案,但它会按照你的要求做,即“在LINQ中做”。

It is also probably not the most efficient solution. 它也可能不是最有效的解决方案。

string FirstName ="John1, John2, John3";
string MiddleInitial = "K1, K2, K3";
string LastName = "Kenndey1, Kenndey2, Kenndey3";
List<String> fn = new List<String>(FirstName.Split(','));
List<String> mi = new List<String>(MiddleInitial.Split(','));
List<String> ln = new List<String>(LastName.Split(','));

IEnumerable<NameDetails> result = from f in fn
        join i in mi on fn.IndexOf(f) equals mi.IndexOf(i)
        join l in ln on fn.IndexOf(f) equals ln.IndexOf(l)
        select new NameDetails {f, i, l};

I used LINQPad to try this out first (with an anonymous class, not the NameDetails calss). 我首先使用LINQPad来尝试这个(使用匿名类,而不是NameDetails calss)。

您可以使用Linq to CSV库。

Further to my previous answer you could also try: 继我之前的回答,您还可以尝试:

// some setup
string firstName ="John1, John2, John3";
string middleInitial = "K1, K2, K3";
string lastName = "Kenndey1, Kenndey2, Kenndey3";
var fn = firstName.Split(',');
var mi = middleInitial.Split(',');
var ln = lastName.Split(',');

// the important bit
var s = fn.Select((f, index) => new NameDetails {f, i = mi[index], l = ln[index]});

It will be fragile to the string arrays having unequal numbers of entries. 具有不等条目数的字符串数组将是脆弱的。

Credit due to a previous answer on SO . 由于之前对SO的回答而产生信用。

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

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