PC Review


Reply
Thread Tools Rate Thread

Concatenate string properties of objects through Linq?

 
 
csharper
Guest
Posts: n/a
 
      1st Sep 2011
Suppose I have a Student class:

public class Student{
public string FirstName { get; set; }
public string LastName { get; set; }
}

And I have a List<Student> students collection.

Now, I'd like to save all students to a text file as FistName + " " + LastName delimited by a comma(,). In other words, the input is this List<Student> students collection, and the output should be something like below:

Aaron Brown, Chris Davidson, Ellen Feliciano, Gary Hutchinson, Ian Jenkins

I know this is very very easy to do using C#. What I am looking for is a single liner LINQ /Lamda expression to achieve this. String.Join(string, string[]) probably won't work since the input is not a string array.

Any idea? Thanks.
 
Reply With Quote
 
 
 
 
csharper
Guest
Posts: n/a
 
      1st Sep 2011

And here is the answer:

string myStudents = String.Join(", ", students.Select(s => s.FirstName + " " + s.LastName));
 
Reply With Quote
 
Arne Vajhøj
Guest
Posts: n/a
 
      2nd Sep 2011
On 9/1/2011 1:45 PM, csharper wrote:
> And here is the answer:
>
> string myStudents = String.Join(", ", students.Select(s => s.FirstName + " " + s.LastName));


There are other ways.

Example:

string myStudents = students.Aggregate("", (tot, nxt) => tot + "," +
nxt.FirstName + " " + nxt.LastName).Substring(1);

But I would probably do it like you did.

Arne
 
Reply With Quote
 
 
 
Reply

Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
LINQ -able objects? Raj Microsoft C# .NET 3 27th May 2010 10:20 PM
linq concatenate query imbirek8 Microsoft C# .NET 1 27th Oct 2008 06:26 AM
pass different LINQ objects (by string name?) to the same(form-)constructor Lextendo Microsoft C# .NET 0 16th Jul 2008 12:06 PM
LINQ: Related objects Dylan Parry Microsoft C# .NET 2 26th Jun 2008 11:19 AM
Concatenate without string or convert string to variable =?Utf-8?B?U1NCU3lzdGVtc0NsZXJr?= Microsoft Access Form Coding 5 6th Apr 2006 11:46 PM


Features
 

Advertising
 

Newsgroups
 


All times are GMT +1. The time now is 06:25 AM.