Linq 聚合函数

发布于 2024-08-31 05:07:38 字数 330 浏览 2 评论 0原文

的列表,

我有一个像“test”、“bla”、“something”、“else”这样

但是当我在上面使用聚合并同时调用一个函数时,在我看来,经过两次“迭代”后,首先被传入?

我像这样使用它:

myList.Aggregate((current, next) => someMethod(current) + ", "+ someMethod(next));

虽然我在 someMethod 函数中放置了一个断点,其中对 myList 中的信息进行了一些转换,但我注意到在第三次调用之后我得到了前一个转换的结果作为输入参数。

I have a List like

"test", "bla", "something", "else"

But when I use the Aggrate on it and in the mean time call a function it seems to me that after 2 'iterations' the result of the first gets passed in?

I am using it like :

myList.Aggregate((current, next) => someMethod(current) + ", "+ someMethod(next));

and while I put a breakpoint in the someMethod function where some transformation on the information in the myList occurs, I notice that after the 3rd call I get a result from a former transformation as input paramter.

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

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

发布评论

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

评论(2

人间不值得 2024-09-07 05:07:38

这就是它的工作方式。

您标记为“当前”的内容意味着迄今为止所积累的所有内容。第一次调用时,种子是第一个元素。

您可以执行以下操作:

var res = myList
   .Aggregate(String.Empty, (accumulated, next) => accumulated+ ", "+ someMethod(next))
   .Substring(2);//take out the first ", "

这样,您只需对每个元素应用一次 someMethod 。

That's the way its intended to work.

What you have labeled current, its meant to be all that have been accumulated so far. On the first call, the seed is the first element.

You could do something like:

var res = myList
   .Aggregate(String.Empty, (accumulated, next) => accumulated+ ", "+ someMethod(next))
   .Substring(2);//take out the first ", "

That way, you only apply someMethod once on each element.

辞取 2024-09-07 05:07:38

如果我的列表是字符串列表,并且我只想返回/操作某些项目,我通常会这样做:

     var NewCollection = MyStringCollection
                             //filter with where clause
                             .Where(StringItem => StringItem == "xyz"
                             //select/manipulate with aggregate
                             .Aggregate(default(string.empty), (av, e) =>
                             {
                                 //do stuff
                                 return av ?? e;
                             });

If my list was a list of strings, and i wanted to return/manipulate only certain items, I would usually do something like this:

     var NewCollection = MyStringCollection
                             //filter with where clause
                             .Where(StringItem => StringItem == "xyz"
                             //select/manipulate with aggregate
                             .Aggregate(default(string.empty), (av, e) =>
                             {
                                 //do stuff
                                 return av ?? e;
                             });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文