Successfully added
C#
by Patrik
Concatenating Property Values from a List in C#
When working with collections in C#, it's common to extract and concatenate specific property values for display or logging purposes. For instance, if you have a list of objects and want to join the values of a particular string property, you can use LINQ in combination with string.Join
.
Scenario
You have a list of objects, each with a Name
property, and you want to create a single comma-separated string of all names.
Solution
Use LINQ to project the property and string.Join
to concatenate the results.
var names = string.Join(", ", items.Select(i => i.Name));
Notes
items
is aList<T>
whereT
has aName
property.Select(i => i.Name)
projects the desired propertyName
from each ItemItem
.string.Join
concatenates the values with a defined separator (e.g.,", "
in this case).- To avoid nulls, you can add
.Where(x => !string.IsNullOrEmpty(x.Name))
.
This method is clean, efficient, and readable—ideal for transforming object data into user-friendly output or log formats.
csharp
linq
string
concatenation
collections
dotnet
Referenced in:
Comments