我们有一个预定义的纸张尺寸列表,例如
PageSize = PageSize.A3, Height = 297, Width = 420
PageSize = PageSize.A4, Height = 210, Width = 297
PageSize = PageSize.A5, Height = 148, Width = 210
PageSize = PageSize.B4, Height = 257, Width = 364
PageSize = PageSize.B5, Height = 182, Width = 257
PageSize = PageSize.LETTER, Height = 216, Width = 279
PageSize = PageSize.LEGAL, Height = 216, Width = 356
PageSize = PageSize.TABLOID, Height = 279, Width = 432
我必须编写一个C#代码,以便从上面输入的纸张尺寸列表中获取最接近的纸张尺寸。
我尝试了什么:
matchedPageSize = (from item in pageSizeMap
where item.Width >= height
where item.Height >= width
let itemSum = item.Width * item.Height
let difference = Math.Abs((height * width) - itemSum)
orderby difference
select item).FirstOrDefault();
if(matchedPageSize == null)
{
matchedPageSize = (from item in pageSizeMap
where item.Width < height
where item.Height < width
let itemSum = item.Width * item.Height
let difference = Math.Abs((height * width) - itemSum)
orderby difference
select item).FirstOrDefault();
}
除了两种情况外,上述逻辑运作良好:
请求您为上述问题提出最佳逻辑建议。
答案 0 :(得分:1)
您可以将每个尺寸的Height
和Width
之间的差异总和与测试尺寸(someSize
)进行比较。
赫普勒:
int GetDifference(int a, int b)
{
return Math.Abs(a - b);
}
查询从最近到最远的排序大小:
var sorted =
pageSizeMap
.OrderBy((s) => GetDifference(s.Height, someSize.Height) + GetDifference(s.Width, someSize.Width))
.ThenBy((s) => Math.Abs(GetDifference(s.Height, s.Width) - GetDifference(someSize.Height, someSize.Width)));
要获得最接近的尺寸:
var nearest = sorted.ElementAt(0);