2011-08-31 113 views
1

大家好我已經得到了目前的電話號碼作爲輸出使用列表: -分組在實體框架MVC

控制器: -

public ActionResult ViewSubRange(int id) 
{ 
    IEnumerable<Number> numbers = context.Numbers.Where(m => m.RangeID == id).ToList(); 

    return View("SubRange", numbers); 
} 

查看: -

@model IEnumerable<TelephoneNumberManagement.Models.Number> 
<table> 
    <tr> 
     <th> 
      Number 
     </th> 
     <th> 
      Status 
     </th> 
    </tr> 

@foreach (var item in Model) 
{ 
    <tr> 
     <td>@item.Number1</td> 
     <td>@item.Status.StatusName</td> 
    </tr> 

} 

</table> 

這很好,但是我注意到我們可以輸出很多數字。我想知道是否可以將數字分組,例如客戶。所以我想達到什麼是一樣的東西: -

01132210000-01132210999客戶A

01132211000-01132211009客戶B

01132211010-01132211029客戶C

+1

我想你需要編寫邏輯來自己組裝羣體 - 有LINQ到組的客戶,但我可以沒有想到任何將一組數字轉換爲描述它們覆蓋的範圍的字符串(禁止簡單的最小/最大值,忽略該範圍是否被覆蓋) – Rup

+0

就像良好的鏈接:http://msdn.microsoft。 com/en-us/vcsharp/aa336746在這裏你可以找到linq使用的很好的例子 –

回答

3

你可以定義一個新視圖模型:

public class MyViewModel 
{ 
    public string StatusName { get; set; } 
    public string Numbers { get; set; } 
} 

然後根據客戶姓名組:

public ActionResult ViewSubRange(int id) 
{ 
    var numbers = context.Numbers 
     .Where(m => m.RangeID == id) 
     .GroupBy(x => x.Status.StatusName) 
     .Select(x => new MyViewModel 
     { 
      StatusName = x.Key, 

      // TODO: could change the format if you will or 
      // select the min and max or whatever you need 
      Numbers = string.Join("-", x.Select(n => n.Number1)) 
     }) 
     .ToList(); 
    return View(numbers); 
} 

終於在自己的看法:

@model IEnumerable<MyViewModel> 
<table> 
    <tr> 
     <th>Number</th> 
     <th>Status</th> 
    </tr> 

    @foreach (var item in Model) 
    { 
     <tr> 
      <td>@item.Numbers</td> 
      <td>@item.StatusName</td> 
     </tr> 
    } 
</table>