To convert a set of strings to a set of integers in C#, you can use LINQ to project each string element to an integer and then create a new HashSet from the projected integers.
In this example,
stringSet
.Select
method to project each string element to an integer using int.Parse
.HashSet
from the projected integers.using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Set of strings
var stringSet = new HashSet<string> { "1", "2", "3", "4", "5" };
// Convert set of strings to set of integers
var intSet = new HashSet<int>(stringSet.Select(int.Parse));
// Print the set of integers
foreach (var i in intSet)
{
Console.WriteLine(i);
}
}
}
1 2 3 4 5
In this example,
stringSet
, including an invalid integer string.Select
method to project each string element to an integer using int.TryParse
to handle errors.Where
method.HashSet
from the valid projected integers.using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Set of strings with an invalid integer string
var stringSet = new HashSet<string> { "1", "2", "3", "invalid", "5" };
// Convert set of strings to set of integers with error handling
var intSet = new HashSet<int>(stringSet.Select(s => {
int.TryParse(s, out int result);
return result;
}).Where(i => i != 0));
// Print the set of integers
foreach (var i in intSet)
{
Console.WriteLine(i);
}
}
}
1 2 3 5
In this tutorial, we learned How to Convert a Set of Strings to a Set of Integers in C# language with well detailed examples.