开发者

LINQ Scalar Operation

Out of curiosity. Can anyone come up with a way to integrate those remaining 开发者_JS百科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;


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.


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);


Replace

.Aggregate((a, b) => a + b); 

with

.Aggregate(0, (a, b) => a + b, x => ((x + 10 - 1) / 10) * 10 - x);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜