简体   繁体   中英

Combining Field Values (Name)

The following will select the name of a user who votes positively on an item and then put it in a comma separated string.

 var string = string.Join(", ", comment.CommentVote.Where(v=> v.Vote == true).Select(v => v.User.FirstName).ToArray());

I want to be able to get the first and last name, put them together, and then list them out in a comma separated list.

Context: I am trying to create something similar to Facebook:

 John Doe and 25 others like this

Where "25 others" provides a list of users on hover. I can loop through the users who voted and get the first and last names, concatenate them, and then add a comma, it just seems like there should be something simpler that lets me avoid the foreach loop.

Just concatenate them:

var str = string.Join(", ", 
                      comment.CommentVote
                             .Where(v=> v.Vote)
                             .Select(v => v.User.LastName + " " + v.User.FirstName));

Besides you don't need to call ToArray() explicitly, as string.Join has an overload accepting IEnumerable<T> . And you cannot have a variable with the name string , as it's an alias for type System.String .

You can just join the to value you want in the select statement.

var results = string.Join(", ", comment.CommentVote.Where(v=> v.Vote)
              .Select(v => string.Format("{0} {1}", v.User.FirstName, v.User.LastName)));

EDIT: Opps sorry, Konstantin Vasilcov already answered

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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