2

I want to create a function that flips a string's order

example: "hi" => "ih"

here is the code I have come out with so far:

public static string Flip(this string Str)
{
  char[] chararray = Str.ToCharArray();
  string output = "";
  chararray. //i dont know what methoud should be used to execute action 
  return output; 
}

the thing is, i want to know within the lambda expression what is the index of the object that is currently selected ex:x in (x => x ) indexOf is not an option as there can be more then one char from the same type

how can I know the index?

edit: I don't want to know how to reverse a string, I want to know how to find an index of an object in lambda expression

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
  • 4
    https://stackoverflow.com/questions/228038/best-way-to-reverse-a-string – fubo Jul 22 '19 at 08:13
  • @fubo read edit –  Jul 22 '19 at 08:16
  • I just wanted to say that there are better approaches than `indexOf` to flip a string – fubo Jul 22 '19 at 08:19
  • You can use [this](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select?view=netframework-4.8#System_Linq_Enumerable_Select__2_System_Collections_Generic_IEnumerable___0__System_Func___0_System_Int32___1__) overload of `Select` method. So you can write `chararray.Select((ch, index) => ...` – Aleks Andreev Jul 22 '19 at 08:19
  • Depending on the linq method you can enter a predicate of the format `Func` where the `Int32` is the index. As example: `test.Where((x, i) => i % 2 == 0)` – NotFound Jul 22 '19 at 08:20
  • @fubo ok cool I thought you want to mark as duplicate –  Jul 22 '19 at 08:20
  • Obligatory post by Tony, I mean Jon Skeet https://codeblog.jonskeet.uk/2009/11/02/omg-ponies-aka-humanity-epic-fail/ – Aron Jul 22 '19 at 08:21
  • @CodeCaster duplicate has nothing to do with my question –  Jul 22 '19 at 08:24

1 Answers1

0

In the Select and Where extension methods of LINQ, you have an overload that takes two parameters in the lambda, the first is the element, the second is the index.

so in your case if you have a char array:

var reversedArray = charArray
         .Select((c, i) => new { Element = c, Index = i })
         .OrderByDescending(arg => arg.Index)
         .Select(arg => arg.Element)
         .ToArray();

This is just to demonstrate how to get the index in LINQ extesions methods. As the question states this is not about how to reverse a string.

Ofir Winegarten
  • 9,215
  • 2
  • 21
  • 27