出于好奇。任何人都可以想出一种方法来将剩余的两行代码与LINQ操作集成吗?
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;
答案 0 :(得分:5)
别。代码已经很清楚了。为什么你想要通过箍来最终得到一些不太可读的东西?
重命名checksum
。类似的东西(你可以想出一个更好的名字;关键是如果它实际上不是校验和,就不要调用第一个计算checksum
):
var intermediate = // your LINQ expression
var rounded = ((intermediate + 10 -1) / 10) * 10;
var checksum = rounded - intermediate;
另外,更改
IsOdd = (index & 1) == 1
到
IsIndexOdd = index % 2 != 0
如果你真的必须知道:
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();
不要这样做。
答案 1 :(得分:1)
你可以通过定义自己的扩展方法来实现它,而不是技术上的linq而是一种类型。正如杰森所说,实际上并没有这样做。
public static class CrazyExtension
{
public S Project<T,S>(this T value, Func<T,S> Selector)
{
return Selector(value);
}
}
然后让您使用:
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);
答案 2 :(得分:-1)
替换
.Aggregate((a, b) => a + b);
与
.Aggregate(0, (a, b) => a + b, x => ((x + 10 - 1) / 10) * 10 - x);