2013-07-30 7 views
0

는 제가 DB에서 배열 제품을 채우기 위해 원하는 컨트롤러를리스트에서 배열을 채우는 방법 <T>?

namespace WebForms 
{ 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Net.Http; 
using System.Web.Http; 

public class ProductsController : ApiController 
{ 

    Product[] products = new Product[] 
    { 
     new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
     new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
     new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
    }; 

    public IEnumerable<Product> GetAllProducts() 
    { 
     return products; 
    } 

    public Product GetProductById(int id) 
    { 
     var product = products.FirstOrDefault((p) => p.Id == id); 
     if (product == null) 
     { 
      throw new HttpResponseException(HttpStatusCode.NotFound); 
     } 
     return product; 
    } 

    public IEnumerable<Product> GetProductsByCategory(string category) 
    { 
     return products.Where(
      (p) => string.Equals(p.Category, category, 
       StringComparison.OrdinalIgnoreCase)); 
    } 
} 
} 

있습니다.

나는 클래스 제품이 있습니다. 내 코드에서 용도 확장 방법 목록 내가리스트와 배열을 채우기 위해 그 코드를 삽입 할 필요가

List<Product> myProducts = new List<Product>(); 
myProducts.FillData(); 

을 채우기 위해?

+0

목록의 내용으로 변환하여 배열로 변환 하시겠습니까? –

+0

또는 사용자 정의 확장 메소드를 구현하고 호출하는 방법을 묻는 중입니까? – tyh

+0

'List .ToArray()'메서드를 사용하십시오. http://msdn.microsoft.com/en-us/library/x303t819.aspx – mao47

답변

2

배열의 크기를 조정할 수 없으므로 어쨌든 새 배열을 만들어야합니다.

그래서 myProductsEnumerable.ToArray()를 사용 괜찮을해야

I가 다른 의견과 대답에 동의
products = myProducts.ToArray(); 
0

단순히 .ToArray()를 호출하고 종료합니다. 그러나 OP가 사용자 정의 확장 메소드에 관심이 있었기 때문에 ...

확장 메서드의 논리를 포함하는 네임 스페이스를 위에서와 같이 새로 작성하십시오.

namespace CustomExtensions 
{ 
    public static class ListExtension 
    { 
     public static void Fill(this List<object> thing) //Must be "this" followed by the type of object you want to extend 
     { 
      //Whatever 
     } 
    } 
} 

다음은 당신이 일을하고있는 곳의 네임 스페이스에 using CustomExtensions를 추가합니다. 지금 당신이 쓸 때 ...

var myList = new List<object>(); 
myList.Fill() 

컴파일러는 불평해서는 안됩니다. 다시 한번 말하지만 이상적인 해결책은 아닙니다. 당신이 요구하는 것이 이미 내장되어 있기 때문입니다.

관련 문제