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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1802227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:58:30  来源:igfitidea点击:

convert comma separated string to list using linq

c#linqstring

提问by Prasad

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? I need this for my asp.net mvc (C#) application.

任何 linq 吗?我的 asp.net mvc (C#) 应用程序需要这个。

采纳答案by rohancragg

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 LINQPadto try this out first (with an anonymous class, not the NameDetails calss).

我首先使用LINQPad进行了尝试(使用匿名类,而不是 NameDetails 类)。

回答by Robert Harvey

You can use the Linq to CSVlibrary.

您可以使用Linq to CSV库。

回答by rohancragg

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 的回答而归功于此。