Old Man
Old Man

Reputation: 3445

Comma separated list from a C# 4.0 List

I have a List of people, and I need a way to make a comma separated list of the person.Email fields

Is there a quick way to do this using c# 4.0?

Upvotes: 0

Views: 290

Answers (4)

Callum Rogers
Callum Rogers

Reputation: 15829

Using some delicious LINQ:

string csv = string.Join(",", people.Select(p => p.Email));

Upvotes: 3

Oscar Mederos
Oscar Mederos

Reputation: 29863

Using LINQ to CSV is extremely easy. Take a look at the link.

All you need to do is place some attributes in the Person class, and you will be able to both read/write from/to .csv easily :)

Here's an example:

var emails =
    from p in people
    select new { p.Email };

cc.Write(emails, @"C:\emails.csv", outputFileDescription)

where outputFileDescription is declared before (take a look at the examples).

Upvotes: 1

Chuck Savage
Chuck Savage

Reputation: 11955

Try:

string csv = string.Join(",", list.Select(p => p.Email).ToArray());

Upvotes: 1

sobby01
sobby01

Reputation: 2164

List<Person> persons = new List<Person>();

persons.Add(new Person { FirstName = "saurabh", LastName = "sharma" });

persons.Add(new Person { FirstName = "sandeep", LastName = "singh" });

persons.Add(new Person { FirstName = "Ivan", LastName = "gupta" });                       

Response.Write(string.Join(",", (from p in persons select p.FirstName).ToArray()));

Upvotes: 0

Related Questions