0

Sorry if not describing clear below because I'm new to C#. I want to do the task that add up all the numbers in the int[] listed below that fetched out via LINQ, and converted into long. the var Sum works good by using lambda operator, but I want to rewrite in an old-school way - don't use any lambda and anonymous functions in Sum2. Can someone show an example of how to write it?

private static void main(string[] args)
    {
        int[] numbers = RandomN(55555);//generate new int[55555]
        var result = 
            from n in numbers
            where n >= 1000
            select n;


        long Sum = result.Sum(j=>(long)j);
        long Sum2 = result.Sum(???);
    }
private int[] randomN(int j){...}
a4194304
  • 366
  • 2
  • 13
  • Why don't simply you use a loop? – t3chb0t Jun 22 '17 at 04:03
  • A lambda expression like `j=>(long)j` is just a shorthand way to write an anonymous method, which it turn is just what it sounds like: a method that has no name (so you can use it only in the context of its declaration). So, to go the other way, you just write a named method that does the same thing. E.g. `result.Sum(CastToLong)` where `long CastToLong(int j) { return j; }`. See marked duplicate for additional information about the relationship between lambda expressions, anonymous methods, and named methods. – Peter Duniho Jun 22 '17 at 04:05
  • I will note that there's really no such thing as an "old school way" to use LINQ that _doesn't_ use lambda expressions. The two were introduced together, and one of the reasons LINQ is so useful is because of the way lambda expressions fit together with it. Attempting to use LINQ without lambda expressions is just goofy. – Peter Duniho Jun 22 '17 at 04:10
  • See also https://stackoverflow.com/questions/208381/whats-the-difference-between-anonymous-methods-c-2-0-and-lambda-expressions and https://stackoverflow.com/questions/299703/delegate-keyword-vs-lambda-notation – Peter Duniho Jun 22 '17 at 04:11

0 Answers0