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 a List<T> where T has a Name property.
  • Select(i => i.Name) projects the desired property Name from each Item Item.
  • 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

Comments