为通用 C# 集合中的每个值调用一个函数

发布于 2024-08-15 05:29:43 字数 201 浏览 3 评论 0原文

我在 List 集合中有一个整数值的集合。 我想为集合中的每个值调用一个函数,其中函数的参数之一是集合值。 如果不在 foreach 循环中执行此操作...有没有办法使用 lambda/linq 表达式来完成此操作?

类似... myList.Where(p => myFunc(p.Value));

提前致谢, -s

I have a collection of integer values in a List collection.
I want to call a function for each value in the collection where one of the function's argument is a collection value.
Without doing this in a foreach loop... is there a way to accomplish this with a lambda/linq expression?

something like... myList.Where(p => myFunc(p.Value)); ?

thanks in advance,
-s

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

一腔孤↑勇 2024-08-22 05:29:43

LINQ 在这里没有帮助,但您可以使用 List。 ForEach

List.ForEach 方法

对列表中的每个元素执行指定的操作。

示例:

myList.ForEach(p => myFunc(p));

传递给 lambda 表达式的值是列表项,因此在此示例中,如果 myList,则 plong列表<长>

LINQ doesn't help here, but you can use List<T>.ForEach:

List<T>.ForEach Method

Performs the specified action on each element of the List.

Example:

myList.ForEach(p => myFunc(p));

The value passed to the lambda expression is the list item, so in this example p is a long if myList is a List<long>.

坦然微笑 2024-08-22 05:29:43

正如其他发帖者所指出的,您可以使用 List.ForEach

但是,您可以轻松编写一个扩展方法,允许您在任何 IEnumerable 上使用 ForEach

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    foreach(T item in source)
        action(item);
}

这意味着您现在可以执行以下操作:

myList.Where( ... ).ForEach( ... );

As other posters have noted, you can use List<T>.ForEach.

However, you can easily write an extension method that allows you to use ForEach on any IEnumerable<T>

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    foreach(T item in source)
        action(item);
}

Which means you can now do:

myList.Where( ... ).ForEach( ... );
野味少女 2024-08-22 05:29:43

是啊!您可以使用 List.ForEach 但问题是它仅适用于列表(当然您可以即时将所有内容更改为列表,但代码越少越好:) )。此外,您必须使用不提供任何返回类型的 Action<> 预测。

无论如何,有一个你想要的答案,你可以用 Func<> 猜测的相同方式使其成为可能,但有一个小技巧如下:

我将即时执行这里的所有操作:

string[] items = (new string[] { "d", "f" }).
    Select(x => new Func<string>(() => { 
        //Do something here...
        Console.WriteLine(x); 
        return x.ToUpper(); 
    }
)).Select(t => t.Invoke()).ToArray<string>();

这里有一些要点:

首先,我动态定义了一个字符串数组,可以用任何支持 LINQ 的集合替换它。

第二,在 Select 内部,将为给定数组的每个元素声明一个 Func,因为它称为 x

查看空括号并记住,当您定义 Func > 总是最后一个类型是返回类型,所以当你只写 Func 时,它表示一个没有输入参数且返回类型为 string 的函数

很明显我们想在给定的数组上使用该函数 (new string[] { "d", "f" }),这就是为什么我定义一个不带参数的函数,并且我也使用了相同的变量Func<> 内部的 x 引用相同的数组元素。

第三,如果您不放置第二个Select,那么您将拥有两个返回字符串的函数的集合,并且它们已经从第一个数组中获取了输入。您可以执行此操作并将结果保存在匿名 变量中,然后调用它们的.Invoke 方法。我写在这里:

var functions = (new string[] { "d", "f" }).
       Select(x => new Func<string>(() => { 
          //Do something here...
          Console.WriteLine(x); 
          return x.ToUpper(); 
       }));
string[] items = functions.Select(t => t.Invoke()).ToArray<string>();

最后,我将结果转换为数组!现在你有了一个字符串数组!

对不起,它变长了!我希望它会有用。

Yap! You can use List.ForEach but the problem is that works only for list (For sure you can change everything to a List on the fly, but less code more fun :) ). Beside, you have to use Action<> prediction that does not provide any return type.

Anyway there is an answer for what you wanted, you can make it possible in the same way you guessed with Func<> but with a tiny trick as below:

I will do everything here on the fly:

string[] items = (new string[] { "d", "f" }).
    Select(x => new Func<string>(() => { 
        //Do something here...
        Console.WriteLine(x); 
        return x.ToUpper(); 
    }
)).Select(t => t.Invoke()).ToArray<string>();

There are some points here:

First, I have defined a string array on the fly that can be replaced by any collection that supports LINQ.

Second, Inside of the Select one Func<string> is going to be declared for each element of the given array as it called x.

(Look at the empty parenthesis and remember that when you define a Func<type**1**, type**2**, ..., type**n**> always the last type is the return type, so when you write just Func<string> it indicates a function that has no input parameter and its return type is string)

It is clear that we want to use the function over the given array (new string[] { "d", "f" }), and that's why I define a function with no parameter and also I have used same variable x inside of Func<> to refer to the same array elements.

Third, If you don't put the second Select then you have a collection of two functions that return string, and already they've got their inputs from the first array. You can do this and keep the result in an anonymous variable and then call their .Invoke methods. I write it here:

var functions = (new string[] { "d", "f" }).
       Select(x => new Func<string>(() => { 
          //Do something here...
          Console.WriteLine(x); 
          return x.ToUpper(); 
       }));
string[] items = functions.Select(t => t.Invoke()).ToArray<string>();

Finally, I've converted the result to an array! Now you have a string array!

Sorry It get long!! I hope it would be useful.

话少情深 2024-08-22 05:29:43

您可以使用 List.ForEach 方法,如下所示:

myList.ForEach(p => myFunc(p));

You could use the List.ForEach method, as such:

myList.ForEach(p => myFunc(p));
山人契 2024-08-22 05:29:43

否 - 如果您想为列表中的每个项目调用函数,则必须为列表中的每个项目调用该函数。

但是,您可以使用 IList.ForEach() 方法作为一点语法糖,使代码的“业务端”更具可读性,如下所示:

items.ForEach(item => DoSomething(item));

No - if you want to call a function for each item in a list, you have to call the function for each item in the list.

However, you can use the IList<T>.ForEach() method as a bit of syntactic sugar to make the "business end" of the code more readable, like so:

items.ForEach(item => DoSomething(item));
云归处 2024-08-22 05:29:43

如果您不想使用 List 的 ForEach 方法,而是使用 IEnumerable (就像人们在“LINQ:ing”时经常做的那样) "),我建议使用 Jon Skeet 等人编写的 MoreLINQ

MoreLINQ 将为您提供 ForEach 和 Pipe(以及一堆其他方法),它对每个元素执行操作,但返回相同的 IEnumerable (与 void 相比)。

If you don't wan't to use the ForEach method of List<T>, but rather use IEnumerable<T> (as one often does when "LINQ:ing"), I suggest MoreLINQ written by Jon Skeet, et al.

MoreLINQ will give you ForEach, and also Pipe (and a bunch of other methods), which performs an action on each element, but returns the same IEnumerable<T> (compared to void).

策马西风 2024-08-22 05:29:43

这是一个迷你(但完整)示例。

public class Employee
{
    public string EmployeeNumber { get; set; }
    public DateTime? HireDate { get; set; }
}
public class EmployeeCollection : List<Employee>
{ }

private void RunTest()
{
    EmployeeCollection empcoll = new EmployeeCollection();
    empcoll.Add(new Employee() { EmployeeNumber = "1111", HireDate = DateTime.Now });
    empcoll.Add(new Employee() { EmployeeNumber = "3333", HireDate = DateTime.Now });
    empcoll.Add(new Employee() { EmployeeNumber = "2222", HireDate = null });
    empcoll.Add(new Employee() { EmployeeNumber = "4444", HireDate = null });

    //Here's the "money" line!
    empcoll.Where(x => x.HireDate.HasValue == false).ToList().ForEach(item => ReportEmployeeWithMissingHireDate(item.EmployeeNumber));

}
private void ReportEmployeeWithMissingHireDate(string employeeNumber)
{
    Console.WriteLine("We need to find a HireDate for '{0}'!", employeeNumber);
}

Here is a mini (yet complete) example.

public class Employee
{
    public string EmployeeNumber { get; set; }
    public DateTime? HireDate { get; set; }
}
public class EmployeeCollection : List<Employee>
{ }

private void RunTest()
{
    EmployeeCollection empcoll = new EmployeeCollection();
    empcoll.Add(new Employee() { EmployeeNumber = "1111", HireDate = DateTime.Now });
    empcoll.Add(new Employee() { EmployeeNumber = "3333", HireDate = DateTime.Now });
    empcoll.Add(new Employee() { EmployeeNumber = "2222", HireDate = null });
    empcoll.Add(new Employee() { EmployeeNumber = "4444", HireDate = null });

    //Here's the "money" line!
    empcoll.Where(x => x.HireDate.HasValue == false).ToList().ForEach(item => ReportEmployeeWithMissingHireDate(item.EmployeeNumber));

}
private void ReportEmployeeWithMissingHireDate(string employeeNumber)
{
    Console.WriteLine("We need to find a HireDate for '{0}'!", employeeNumber);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文