Method 1: Using String.Join()
The String.Join()
method is used to concatenate elements of a collection into a single string. This method takes care of handling separators between the elements.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
string result = string.Join(", ", numbers);
Console.WriteLine("Using String.Join():");
Console.WriteLine(result);
}
}
Output:
Using String.Join():
1, 2, 3, 4, 5
Method 2: Using LINQ
LINQ (Language Integrated Query) provides a short way to manipulate collections in C#. You can use the Aggregate
method to concatenate elements into a string.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
string result = numbers.Aggregate((current, next) => current + ", " + next);
Console.WriteLine("Using LINQ:");
Console.WriteLine(result);
}
}
Output:
Using LINQ:
1, 2, 3, 4, 5
Method 3: Custom Implementation
You can also create a custom method to convert a collection to a string based on specific requirements. This gives you complete control over the formatting.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
string result = ConvertCollectionToString(numbers);
Console.WriteLine("Using Custom Implementation:");
Console.WriteLine(result);
}
static string ConvertCollectionToString<T>(IEnumerable<T> collection)
{
// Custom logic for formatting the string
return string.Join(" | ", collection);
}
}
Output:
Using Custom Implementation:
1 | 2 | 3 | 4 | 5
Comments (0)