Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert comma separated string to list using linq

Tags:

string

c#

linq

I have 3 comma separated strings FirstName, MiddleInitial, LastName

I have a class 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.

Any linq for this? I need this for my asp.net mvc (C#) application.

like image 447
Prasad Avatar asked Nov 26 '09 08:11

Prasad


People also ask

How to convert string with comma to List in C#?

To convert a delimited string to a sequence of strings in C#, you can use the String. Split() method. Since the Split() method returns a string array, you can convert it into a List using the ToList() method.


2 Answers

I don't neccesarily advocate this as a good solution but it does what you asked, which is to 'do it in 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).

like image 130
rohancragg Avatar answered Nov 11 '22 14:11

rohancragg


You can use the Linq to CSV library.

like image 42
Robert Harvey Avatar answered Nov 11 '22 13:11

Robert Harvey