【发布时间】:2017-01-16 14:43:17
【问题描述】:
我们有一个预定义的纸张尺寸列表,例如
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();
}
上述逻辑运行良好,除了以下两种情况:
- 当高度小于所有上述高度且宽度大于所有上述宽度时。例如高度:50,宽度:500
- 当高度大于上述所有高度和宽度时 小于上述所有宽度。例如高度:400,宽度:150
请求您就上述问题提出最佳逻辑。
【问题讨论】:
-
@Roma:是的,这是第一个案例。问题也在于 500X100 尺寸。
-
第二次选择后检查 if(matchedPageSize == null)。现在这将意味着没有覆盖用户区域的预定义大小。但是从您的帖子来看,目前尚不清楚在这种情况下该怎么做。
-
您需要准确定义决定选择哪种尺寸的逻辑。然后写代码
-
@Saket,看看我的回答。该解决方案应该适合您。