Cast IEnumerable<string> to IEnumerable<int> in C# [duplicate] - c#

This question already has answers here:
How to convert List<string> to List<int>?
(15 answers)
Closed 5 years ago.
I have:
IEnumerable<string> c = codigo_incidencia.Split('#');
I need to cast "c" to be an IEnumerable<int>. I donĀ“t know how to do this cast in C#.
Can someone help me?

Shortest way is to using linq .Select likewise:
var c = codigo_incidencia.Split('#').Select(int.Parse);
If you are not sure that the sections are valid ints then you'd want to use a TryParse as in: Select parsed int, if string was parseable to int. And if working with C# 7.0 you can look at this answer of the question:
var result = codigo_incidencia.Split('#')
.Select(s => new { Success = int.TryParse(s, out var value), value })
.Where(pair => pair.Success)
.Select(pair => pair.value);

Use LINQ:
IEnumerable<int> c = codigo_incidencia.Split('#').Select(x => int.Parse(x));

You can do it like this if the strings are always guaranteed to be numbers:
IEnumerable<int> c = codigo_incidencia.Split('#').Select(stringValue => int.Parse(stringValue));

Related

Another method to verify an Anagram [duplicate]

This question already has answers here:
Sorting a C# List<> without LINQ or delegates
(1 answer)
Better way to sort array in descending order
(7 answers)
Simple bubble sort c#
(18 answers)
Closed 16 days ago.
I have a very simple and silly test that is to compare two strings and check if it is an anagram.
I found this question, bt besides being old, it has no correct answer.
This using LINQ.
This not solve my question.
I managed to solve it using LINQ and also using a foreach, but the next challenge is to do it using sorting (without using LINQ). An anagram is a word or phrase formed by rearranging the letters of a different word or phrase. We can generalize this in string processing by saying that an anagram of a string is another string with exactly the same quantity of each character in it, in any order.
How can I sort without using LINQ?
private static bool CheckAnagramWithLinq(string texto1, string texto2)
{
return texto1.ToList().Intersect(texto2.ToList()).ToList().Count == texto1.Length;
}
private static bool CheckAnagramaWithoutLinq(string texto1, string texto2)
{
var charArray = texto1.ToCharArray();
foreach (var caracter in charArray)
{
if (texto2.Contains(caracter) && texto1.Count(x => x == caracter) == texto2.Count(x => x == caracter))
continue;
return false;
}
return true;
}
Works for me:
private static bool CheckAnagram(string text1, string text2)
{
var aa = string.Concat(text1.OrderBy(c => c));
var bb = string.Concat(text2.OrderBy(c => c));
return aa == bb;
}

C# Equivalent to Python's map()? [duplicate]

This question already has answers here:
Assign values of array to separate variables in one line
(8 answers)
Closed 4 years ago.
Normally in Python 2/3 we may use the following code to split two space-separated integers into two variables:
a,b = map(int,input().split())
Is there a short C# equivalent to this? (i.e nothing as long as below)
string[] template = Console.ReadLine().Split();
a = Convert.ToInt32(template[0]);
b = Convert.ToInt32(template[1]);
You could try this:
var result = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
However, the above code would crash if the input is not valid.
A more fault tolerant approach would be the following:
var result = Console.ReadLine()
.Split(' ')
.Select(input =>
{
int? output = null;
if(int.TryParse(input, out var parsed))
{
output = parsed;
}
return output;
})
.Where(x => x != null)
.Select(x=>x.Value)
.ToArray();
It's called Select(). You need to import Linq:
using System.Linq;
Then you can use it similar to map. Be aware that it is an extension function and is not the exact equivalent.
var integers = Console.ReadLine().Split().Select(s => Convert.ToInt32(s)).ToArray();
var a = integers[0];
var b = integers[1];
This example lacks any proper error handling.
Edit
Add ToArray()
Write out lambda, which is needed due to the overloads of Convert.ToInt32

Determine List.IndexOf ignoring case [duplicate]

This question already has answers here:
Case-Insensitive List Search
(8 answers)
Closed 6 years ago.
Is there a way to get the index of a item within a List with case insensitive search?
List<string> sl = new List<string>() { "a","b","c"};
int result = sl.IndexOf("B"); // should be 1 instead of -1
Try this : So there is no direct way to use IndexOf with String Comparison option for LIST, to achieve desire result you need to use Lambda expression.
int result = sl.FindIndex(x => x.Equals("B",StringComparison.OrdinalIgnoreCase));
The IndexOf method for Strings in C# has a ComparisonType argument, which should work something like this:
sl.IndexOf("yourValue", StringComparison.CurrentCultureIgnoreCase)
or
sl.IndexOf("yourValue", StringComparison.OrdinalIgnoreCase)
Documentation for this can be found here and here

How to sort Strings in C# [duplicate]

This question already has answers here:
C# sort Arraylist strings alphabetical and on length
(5 answers)
Closed 6 years ago.
I have to sort an array of strings. How can I do that, if:
They must be placed in order of string length.
If lengths are equal, the must be placed alphabetically.
Is there any simple to do that ?
Here's the traditional way in C# ...
static void Main(string[] args)
{
List<string> list = new List<string>();
list.Add("1991728819928891");
list.Add("0991728819928891");
list.Add("3991728819928891");
list.Add("2991728819928891");
list.Add("Hello");
list.Add("World");
list.Add("StackOverflow");
list.Sort(
delegate (string a, string b) {
int result = a.Length.CompareTo(b.Length);
if (result == 0 )
result = a.CompareTo(b);
return result;
}
);
Console.WriteLine(string.Join("\n", list.ToArray()));
}
Sample Output:
Hello
World
StackOverflow
0991728819928891
1991728819928891
2991728819928891
3991728819928891
You can do it with LINQ in the following way:
string[] arr = new[] { "aa", "b", "a" , "c", "ac" };
var res = arr.OrderBy(x => x.Length).ThenBy(x => x).ToArray();
Another way is to use Array.Sort with custom IComparer implementation.

change string type list to type integer [duplicate]

This question already has answers here:
Converting a List<String> to List<int>
(2 answers)
Closed 9 years ago.
The list is below: I simply want to convert it to an integer list
List<string> list2 = new List<string>();
How do I convert all of it's contents to int?
var intList = list2.Select(x => int.Parse(x)).ToList();
You can use List.ConvertAll<int>:
List<int> ints = list2.ConvertAll<int>(int.Parse);
If you don't have a list you could use a Select with int.Parse:
List<int> ints = strings.Select(s=> int.Parse(s)).ToList();

Categories