【发布时间】:2018-09-19 16:29:33
【问题描述】:
所以我有这个 C# 代码:
static void Main(string[] args)
{
string @string = "- hello dude! - oh hell yeah hey what's up guy";
Console.WriteLine(String.Join(".", @string.GetSubstringsIndexes("he")));
Console.Read();
}
添加扩展“GetSubstringsIndexes”方法的部分类:
partial class StringExtension
{
public static int[] GetSubstringsIndexes(this string @string, string substring)
{
List<int> indexes = new List<int>(@string.Length / substring.Length);
int result = @string.IndexOf(substring, 0);
while (result >= 0)
{
indexes.Add(result);
result = @string.IndexOf(substring, result + substring.Length);
}
return indexes.ToArray();
}
}
我希望它是一个在 String.Join 方法的参数括号中的 lambda 表达式,而不是调用我编写的函数。
我的意思是,我不想写这个函数然后调用它,而是写一个 lambda 表达式只使用一次!
我希望它看起来如何的示例:
static void Main(string[] args)
{
string @string = "- hello dude! - oh hell yeah hey what's up guy";
Console.WriteLine(String.Join(".", () => {List<int> ind = new List<int>()..... AND SO ON...} ));
Console.Read();
}
嗯,实际上,我刚刚意识到(在写这个问题时)对于这种情况是不必要的,因为我的 GetSubStringsIndexes 方法太大了。但想象一下,如果它很短。
请告诉我是否可以做这样的事情,如果可以,请告诉我如何做!
编辑:
我已经完成了,看起来就是这样:
Console.WriteLine(String.Join(".", ((Func<int[]>)
( () =>
{
List<int> indx = new List<int>();
int res = @string.IndexOf("he", 0);
while (res >= 0)
{
indx.Add(res);
res = @string.IndexOf("he", res + "he".Length);
}
return indx.ToArray();
}
))()));
【问题讨论】:
-
您想在此时执行一段代码并将结果传递给 string.join?
-
是的,这正是我想做的。
标签: c# lambda functional-programming