gpt4 book ai didi

C# 有 foreach oneliner 可用吗?

转载 作者:可可西里 更新时间:2023-11-01 03:11:56 25 4
gpt4 key购买 nike

我只想知道C#里有没有foreach oneliner,比如if oneliner (<em>exp</em>) ? <em>then</em> : <em>else</em> .

最佳答案

如果你正在处理一个数组,那么你可以使用内置的静态 ForEach 方法:

Array.ForEach(yourArray, x => Console.WriteLine(x));

如果您正在处理 List<T>那么你可以使用内置的 ForEach 实例方法:

yourList.ForEach(x => Console.WriteLine(x));

没有任何内置的东西可以对抗任意 IEnumerable<T>序列,但如果您觉得需要它,也很容易推出您自己的扩展方法:

yourSequence.ForEach(x => Console.WriteLine(x));

// ...

public static class EnumerableExtensions
{
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
if (source == null) throw new ArgumentNullException("source");
if (action == null) throw new ArgumentNullException("action");

foreach (T item in source)
{
action(item);
}
}
}

关于C# 有 foreach oneliner 可用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4793885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com