【问题标题】:How to find the index of an element in an array inside a lambda expression in c# [duplicate]如何在c#中的lambda表达式中查找数组中元素的索引[重复]
【发布时间】:2019-11-30 04:06:37
【问题描述】:

我想创建一个翻转字符串顺序的函数

例如:"hi" => "ih"

这是我目前得到的代码:

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

问题是,我想知道在 lambda 表达式中当前选择的对象的索引是什么,例如:x in (x => x ) indexOf 不是一个选项,因为可以有多个字符来自同一类型

我怎么知道索引?

编辑: 我不想知道如何反转字符串,我想知道如何在 lambda 表达式中找到对象的索引

【问题讨论】:

  • @fubo 阅读编辑
  • 我只是想说有比indexOf 更好的方法来翻转字符串
  • 你可以使用this重载的Select方法。所以你可以写chararray.Select((ch, index) => ...
  • 根据 linq 方法,您可以输入格式为 Func<TSource,Int32,Boolean> 的谓词,其中 Int32 是索引。例如:test.Where((x, i) => i % 2 == 0)

标签: c# arrays linq indexing lambda


【解决方案1】:

在 LINQ 的 SelectWhere 扩展方法中,您有一个在 lambda 中接受两个参数的重载,第一个是元素,第二个是索引。

所以如果你有一个char 数组:

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

这只是为了演示如何在 LINQ 扩展方法中获取索引。 正如问题所述,这与如何反转字符串无关。

【讨论】:

    猜你喜欢
    • 2014-09-16
    • 2016-12-29
    • 1970-01-01
    • 2017-12-01
    • 2019-12-31
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多