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

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

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;
}

Reverse an Array order and print it C# [duplicate]

This question already has answers here:
How to reverse an array using the Reverse method. C# [closed]
(6 answers)
Closed 6 months ago.
using System;
using System.Linq;
namespace Array.ReversingArrayChar
{
class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
char[] symbol = input.Split(' ').Select(char.Parse).ToArray();
symbol.Reverse();
for (int a = 0; a <= symbol.Length - 1; a++)
{
Console.Write(symbol[a] + " ");
}
}
}
}
When I run the code I get the Array printed but not in reversed order even tho I used .Reverse(). It's probably a really simple mistake but it's too late at night for my brain to figure it out.
Enumerable.Reverse is a LINQ extension that returns the sequence reversed, so you have to assign it to a variable. But here you want to use Array.Reverse:
Array.Reverse(symbol);
Use Enumerable.Reverse if you don't want to modify the original collection and if you want to support any kind of sequence. Use List.Reverse or Array.Reverse if you want to support only these collections and you want to modify it directly. Of course this is more efficient since the method knows the size and you need less memory.
Oh Man..! you are almost there, your code is fine but you need to use the output of the .Reverse() method. since the method won't modify the actual collection, it will return the reversed array. you can try the following:
string input = "A S D R F V B G T";
char[] symbols = input.Split(' ').Select(char.Parse).ToArray();
foreach (var symbol in symbols.Reverse())
{
Console.Write(symbol + " ");
}
You will get the output as T G B V F R D S A

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

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));

Visual C# converting custom IEnumerable to string[]

I am writing a plugin code in C# and there is a custom IEnumerable that is in fact an array of strings. However no string operations can be done on the array elements because they are not of the type <string>. But I need them to be strings and I have to operate on them as strings.
So I have added these 2 lines of code to turn the array into string:
var arrayRawSourceText = EditorController.ActiveDocument.ActiveSegmentPair.Source.AllSubItems.ToArray();
string[] arraySourceText = new string[arrayRawSourceText.Length];
for (int i = 0; i < arrayRawSourceText.Length; i++) { arraySourceText[i] = arrayRawSourceText[i].ToString(); }
Only two lines, yet I wonder if there is a simpler way of converting the array to <string>. Like a lambda expression or any other way to make this simpler.
If AllSubItems implement IEnumerable I guess this code snippet should work :
var arraySourceText = EditorController.ActiveDocument
.ActiveSegmentPair
.Source
.AllSubItems
.Select(t => t.ToString())
.ToArray();
I have seen you already accepted an answer, But for further searchers maybe this will fit too:
var arraySourceText = EditorController.ActiveDocument
.ActiveSegmentPair
.Source
.AllSubItems
.Cast<string>()
.ToArray();

Can you reverse order a string in one line with LINQ or a LAMBDA expression

Not that I would want to use this practically (for many reasons) but out of strict curiousity I would like to know if there is a way to reverse order a string using LINQ and/or LAMBDA expressions in one line of code, without utilising any framework "Reverse" methods.
e.g.
string value = "reverse me";
string reversedValue = (....);
and reversedValue will result in "em esrever"
EDIT
Clearly an impractical problem/solution I know this, so don't worry it's strictly a curiosity question around the LINQ/LAMBDA construct.
Well, I can do it in one very long line, even without using LINQ or a lambda:
string original = "reverse me"; char[] chars = original.ToCharArray(); char[] reversed = new char[chars.Length]; for (int i=0; i < chars.Length; i++) reversed[chars.Length-i-1] = chars[i]; string reversedValue = new string(reversed);
(Dear potential editors: do not unwrap this onto multiple lines. The whole point is that it's a single line, as per the sentence above it and the question.)
However, if I saw anyone avoiding using framework methods for the sake of it, I'd question their sanity.
Note that this doesn't use LINQ at all. A LINQ answer would be:
string reverseValue = new string(original.Reverse().ToArray());
Avoiding using Reverse, but using OrderByDescending instead:
string reverseValue = new string(original.Select((c, index) => new { c, index })
.OrderByDescending(x => x.index)
.Select(x => x.c)
.ToArray());
Blech. I like Mehrdad's answer though. Of course, all of these are far less efficient than the straightforward approach.
Oh, and they're all wrong, too. Reversing a string is more complex than reversing the order of the code points. Consider combining characters, surrogate pairs etc...
I don't see a practical use for this but just for the sake of fun:
new string(Enumerable.Range(1, input.Length).Select(i => input[input.Length - i]).ToArray())
new string(value.Reverse().ToArray())
var reversedValue = value.ToCharArray()
.Select(ch => ch.ToString())
.Aggregate<string>((xs, x) => x + xs);
Variant with recursive lambda:
var value = "reverse me";
Func<String, String> f = null; f = s => s.Length == 1 ? s : f(s.Substring(1)) + s[0];
var reverseValue = f(value);
LP,
Dejan
You can use Aggregate to prepend each Char to the reversed string:
"reverse me".Aggregate("", (acc, c) => c + acc);
var reversedValue= "reverse me".Reverse().ToArray();
In addition to one previous post here is a more performant solution.
var actual0 = "reverse me".Aggregate(new StringBuilder(), (x, y) => x.Insert(0, y)).ToString();
public static string Reverse(string word)
{
int index = word.Length - 1;
string reversal = "";
//for each char in word
for (int i = index; index >= 0; index--)
{
reversal = reversal + (word.Substring(index, 1));
Console.WriteLine(reversal);
}
return reversal;
}
Quite simple. So, from this point on, I have a single method that reverses a string, that doesn't use any built-in Reverse functions.
So in your main method, just go,
Console.WriteLine(Reverse("Some word"));
Technically that's your one liner :P
If we need to support combining characters and surrogate pairs:
// This method tries to handle:
// (1) Combining characters
// These are two or more Unicode characters that are combined into one glyph.
// For example, try reversing "Not nai\u0308ve.". The diaresis (¨) should stay over the i, not move to the v.
// (2) Surrogate pairs
// These are Unicode characters whose code points exceed U+FFFF (so are not in "plane 0").
// To be represented with 16-bit 'char' values (which are really UTF-16 code units), one character needs *two* char values, a so-called surrogate pair.
// For example, try "The sphere \U0001D54A and the torus \U0001D54B.". The 𝕊 and the 𝕋 should be preserved, not corrupted.
var value = "reverse me"; // or "Not nai\u0308ve.", or "The sphere \U0001D54A and the torus \U0001D54B.".
var list = new List<string>(value.Length);
var enumerator = StringInfo.GetTextElementEnumerator(value);
while (enumerator.MoveNext())
{
list.Add(enumerator.GetTextElement());
}
list.Reverse();
var result = string.Concat(list);
Documentation: MSDN: System.Globalization.StringInfo Class
string str="a and b";
string t="";
char[] schar = str.Reverse().ToArray();
foreach (char c in schar )
{
test += c.ToString();
}

Categories