Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Scalar Operation

Tags:

c#

linq

Out of curiosity. Can anyone come up with a way to integrate those remaining two lines of code with the LINQ operation?

var code = string.Format("{0:00000}{1:000000000}{2:0000000}", SelectedPreset.Prefix, i, SelectedPreset.Amount);

// calculate checksum
var checksum = code
    .Reverse()
    .Select((c, index) => new { IsOdd = (index & 1) == 1, Value = (int) Char.GetNumericValue(c) })
    .Select(x => x.IsOdd ? x.Value : x.Value*3)
    .Aggregate((a, b) => a + b);

var rounded = ((checksum + 10 - 1)/10)*10;
checksum = rounded - checksum;
like image 606
Oliver Weichhold Avatar asked Dec 10 '25 14:12

Oliver Weichhold


2 Answers

Don't. The code is pretty clear already. Why would you want to jump through hoops to end up with something that is going to be less readable?

Rename checksum though. Something like (you can come up with a better name; the point is to just not call the first calculation checksum if it's not actually the checksum):

var intermediate = // your LINQ expression
var rounded = ((intermediate + 10 -1) / 10) * 10;
var checksum = rounded - intermediate;

Also, change

IsOdd = (index & 1) == 1

to

IsIndexOdd = index % 2 != 0

And if you really must know:

 var checksum =
     new [] {
         code
            .Reverse()
            .Select((c, index) => new {
                IsIndexOdd = index % 2 != 0,
                Value = (int) Char.GetNumericValue(c)
            })
            .Select(x => x.IsIndexOdd ? x.Value : 3 * x.Value)
            .Aggregate((a, b) => a + b)
     }
     .Select(x => new { Rounded = ((x + 10 - 1) / 10) * 10, Intermediate = x })
     .Select(x => x.Rounded - x.Intermediate)
     .Single();

Don't do this.

like image 70
jason Avatar answered Dec 12 '25 04:12

jason


You could do it by defining your own extension method, not technically linq but sort of. As Jason said, don't actually do this.

public static class CrazyExtension
{
    public S Project<T,S>(this T value, Func<T,S> Selector)
    {
        return Selector(value);
    }
}

This then lets you use:

 var checksum =
         code
         .Reverse()
         .Select((c, index) => new { IsOdd = (index & 1) == 1, Value = (int) Char.GetNumericValue(c) })
         .Select(x => x.IsOdd ? x.Value : x.Value*3)
         .Aggregate((a, b) => a + b)
         .Project(x => new { Rounded = ((x + 10 - 1) / 10) * 10, Intermediate = x })
         .Project(x => x.Rounded - x.Intermediate);
like image 40
ForbesLindesay Avatar answered Dec 12 '25 05:12

ForbesLindesay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!