我自己正在学习 C#,我想知道 C# 方法是否可以像 Python 一样快速解析值列表,如下所示:
def myMethod(somevalue):
return somevalue * 2
x = [1,2,3,4,5]
a = [myMethod(i) for i in x]
目前我正在尝试创建一个类,该类的方法接受 double 值。 但是如果 x 是一个列表呢?
class myClass
{
public double somevalue;
public myClass(double someValue)
{
somevalue = someValue;
}
public double myMethod()
{
return somevalue * 2;
}
}
myClass output = new myClass(x);
A = output.myMethod();
我的问题是,C# 能否创建非常简洁的代码,使方法接受列表、遍历列表并给出结果列表?
最佳答案
不是 python 专家,而是这个:
def myMethod(somevalue):
return somevalue * 2
x = [1,2,3,4,5]
a = [myMethod(i) for i in x]
在 C# 中看起来是这样的:
//either:
double TimesTwo(double d) => d * 2; //a method declaration that is "expression bodied" style
//or:
double TimesTwo(double d) { return d * 2; } //a method declaration that is "normal" style
void SomeOtherMethod(){ //these statements can't just be floating around in a namespace like the method declarations above, they have to be inside some other method
var x = new[] {1d,2,3,4,5}; //the first element is a double (1d), the others will be promoted from int to double without needing an explicit cast, the whole array x is a double[]
var a = x.Select(TimesTwo).ToArray();
}
您可以跳过为 * 2
创建单独的方法操作(上面的方法称为 TimesTwo),只需将您想要的逻辑放入内联:
var x = new[] { 1d,2,3,4,5 };
var a = x.Select(p => p * 2).ToArray();
p => p * 2
类似于“内联方法”——我们将它们称为 lambda;输入参数称为 p
它的类型是从 .Select
的集合类型推断出来的被调用。在本例中为 double
推断,因为 x
是 double
数组
return
关键字未在单行 lambda 中指定(我们将其称为 expression bodied something); =>
之后的单行代码(在 p => ...
和 TimesTwo(int i) => ...
中)是解析为一个值的语句,并且该值被隐式返回。在这种情况下声明 p => p * 2
乘以输入 p
2,自动返回结果。
.Select
的结果method 是一个可枚举的(具体类型为 IEnumerable<double>
, ToArray()
方法将枚举它并将其转换为数组。正是 ToArray 的调用导致 p*2
在每个成员上被调用,并且 ToArray 收集所有结果并输出一个数组
所有这些代码都来自 System.Linq
中的扩展方法命名空间,因此您的代码需要 using System.Linq;
在顶部
重要的一点,在未来的某个时候可能会很重要; 如果 Select 的可枚举输出实际上未被枚举,则 Select 中的 lambda 代码不会执行。如果你有:
var enumerableThing = oneThousandThings.Select(p => SomeOperationThatTakesOneSecond(p));
它会立即执行;该行代码中没有任何内容枚举结果可枚举,没有为新数组分配内存,没有发生任何循环集合,需要 1 秒的操作甚至没有被调用一次,更不用说一千次了。
如果您稍后做了一些实际枚举结果的事情,那么操作将花费一千秒:
var arr = enumerableThing.ToArray() //takes 1000s
foreach(var x in enumerableThing) //would take 1000s to finish looping
...
int i = 500;
foreach(var x in enumerableThing){ //would take 500s, the enumeration quitting early after being half done
i--;
if(i == 0) break;
}
这种枚举可以在数小时或数天后完成;它称为延迟执行,如果您不熟悉它,值得进一步研究
关于c# - 如何使用只接受一个项目的 C# 方法快速解析列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70500649/