-3

Is there a way I can make this code more compact with a lambda or an anonymous function or something like that?

static int chancesTotal = _total_chances();
static int _total_chances()
{
    int x = 0;
    foreach (var c in chances)
        x += c.Value;
    return x;
}

That is, I'd like something like

int chancesTotal = () =>
{
    int x = 0;
    foreach (var c in chances)
        x += c.Value;
    return x;
}();

But it doesn't work.


Edit: this solution proposed by @pinkfloydx33 is close to what I had asked.

using System;
using System.Collections.Generic;


List<int> chances = new List<int>();

int chancesTotal = ((Func<int>)(() =>
{
    int x = 0;
    foreach (var c in chances)
        x += c;
    return x;
}))();
mg979
  • 43
  • 5
  • 1
    `return chances.Sum(c => c.Value)` – pinkfloydx33 Mar 11 '21 at 12:45
  • using `System.Linq` – demo Mar 11 '21 at 12:46
  • 1
    Firstly, why do you need it more compact... and secondly, why haven't you looked at the documentation for enumerable, it's very easy to read – TheGeneral Mar 11 '21 at 12:49
  • Fun fact, linq doesn't mean faster, in a lot of cases it allocates because of the lambda and generated classes, and it does what you can do in in a loop yet less efficently, If you do want something more succinct then you should be looking st thr documentation – TheGeneral Mar 11 '21 at 12:54
  • 1
    Here's the "equivalent" of what you say you want. Note that it's not very compact at all https://sharplab.io/#v2:C4LgTgrgdgPgAgJgAwFgBQiCM65IARyYAsA3OuWgDICWAzsADzVTAD8AfHgMYAWAhlC4BTWngC8eKEIDuACgCUZNOmbBu/QSIAqAe2B8ANuLyzZcAKxMW7eafnj26AN7o8bvKrwAPY0iXu8ADMdMCE+XhMANz4wbg8odQFhWnlXAPcfAGoJLgA6ADVDCCF/dzgAdm8lAF95W0UgA – pinkfloydx33 Mar 11 '21 at 14:15
  • @pinkfloydx33 thanks that's the answer I was looking for. But you're right in that it isn't a very convenient alternative. – mg979 Mar 11 '21 at 14:27

1 Answers1

0
static int chancesTotal = chances.Sum(c => c.Value);
Spotted
  • 4,021
  • 17
  • 33
  • Thanks, this works in this case but I was looking for a more general answer. – mg979 Mar 11 '21 at 13:10
  • @mg979 Ok, I understand. I don't believe there is a less verbose solution in C# than the one proposed by pinkfloydx33. – Spotted Mar 12 '21 at 07:11