2017-01-16 151 views
1

我們有一個預先定義的紙張尺寸列表,例如,從可用紙張尺寸列表中獲取最近的紙張尺寸

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

上述邏輯運作良好,除了在兩種情況下:

  1. 當高度小於上面提到的所有高度和寬度大於所有上述寬度。對於例如高度:50,寬度:500
  2. 當高度超過上述所有高度時,寬度爲 小於上述所有寬度。對於例如高度:400,寬度:150

請求您爲上述問題建議最佳邏輯。

+0

@Roma:是的,這是第一個案例。此外,問題與500X100大小。 – Saket

+0

檢查第二次選擇後是否(matchedPageSize == null)。現在這意味着沒有預定義的大小覆蓋用戶的區域。但是從你發佈的情況來看,不清楚在這種情況下要做什麼。 –

+0

您需要準確定義您的邏輯是用於決定選擇哪種尺寸。然後寫代碼 –

回答

1

您可以比較每種尺寸的HeightWidth與測試尺寸(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);     
+0

假設預定義的尺寸(高度,寬度)分別爲33,11和200,100。在這種情況下,按照上述邏輯,最近的紙張尺寸將是200,100;但預計應該是33,11。我對麼? – Saket

+0

@Saket,是的,你是對的。該算法以錯誤的方式工作。我會嘗試另一個。這對我來說是非常有趣的問題) –

+0

感謝您的努力。真的很感激它。 – Saket

相關問題