2011-10-28 3 views
0
switch(ID) 
{ 
    case "CustomReportsContainer": 
     foreach (var report in SessionRepository.Instance.CustomReports.ToList()) 
     { 
      var reportItem = new RadListBoxItem(report.Name, report.ID.ToString()); 
      if (!Items.Any(item => int.Equals(item.Value, reportItem.Value))) 
      { 
       Items.Add(reportItem); 
      } 
     } 
     break; 
    case "HistoricalReportsContainer": 
     foreach (var report in SessionRepository.Instance.HistoricalReports.ToList()) 
     { 
      var reportItem = new RadListBoxItem(report.Name, report.ID.ToString()); 
      if (!Items.Any(item => int.Equals(item.Value, reportItem.Value))) 
      { 
       Items.Add(reportItem); 
      } 
     } 
     break; 
} 

HistoricalReports 및 CustomReports는 다양한 유형의 콜렉션이지만 각 객체 유형과 동일한 두 가지 속성에 관심이 있습니다. LINQ의 Select를 사용하고 익명으로 형식이 지정된 개체 목록을 만들 수 있어야한다고 생각했습니다.익명 형식을 사용하여보다 간결하게 표현할 수 있습니까?

암시 적으로 입력 된 변수는 할당하지 않고 만들 수 없습니다. 그리고 Switch 문 범위 안에 있기 때문에 ... switch 문 내부에서 var에 할당 할 수없고 switch 문 외부에서 나머지 코드를 옮길 수 없습니다.

이 코드를 어떻게 표현해야합니까? 현재의 구현이 '최상'인가?

위 클로. 이것으로 무엇이든 할 수 있습니까? API를 통해 진행되므로 더 이상 수정할 수 없습니다. 항목이 인터페이스 또는 기본 유형을 공유 (또는 그들이 있도록 변경할 수 있습니다) 경우

ReportServices.GetAllCustomReports().Select(report => new { report.Name, report.ID}).ToList().ForEach(customReport => _customReports.Add(customReport)); 

Error 2 Argument 1: cannot convert from 'AnonymousType#1' to 'CableSolve.Web.Dashboard.IReport' 
+0

전혀 도움이되지 않습니다! 나는 지금 리팩토링 중입니다. 그래서 내가 여기에 있고, 질문하고 배우는 중입니다. –

답변

4

CustomReportHistoricalReport가 (최소한)를 Id 및 특성 NameIReport를 포함하는 인터페이스를 구현한다.

switch(ID) 
{ 
    case "CustomReportsContainer": 
     AddReportItems(SessionRepository.Instance.CustomReports); 
     break; 
    case "HistoricalReportsContainer": 
     AddReportItems(SessionRepository.Instance.HistoricalReports); 
     break; 
} 

private void AddReportItems(IEnumerable<IReport> reports) 
{ 
    foreach (var report in reports) 
    { 
     var reportItem = new RadListBoxItem(report.Name, report.ID.ToString()); 
     if (!Items.Any(item => int.Equals(item.Value, reportItem.Value))) 
     { 
      Items.Add(reportItem); 
     } 
    } 
} 

편집 GetAllCustomReportsIReport 인터페이스를 구현하는 형식을 반환하기 위해 추가 질문에 대한 응답으로

, 그것은 가능한 것입니까? 그러면 Select(report => new { report.Name, report.ID})을 통해 익명 유형으로 예상 할 필요가 없어지고 나머지 문제가 해결됩니다.

+0

예를 들어 주셔서 감사합니다! :) –

+0

그래서 저는 정말 가깝습니다.이 인터페이스를 사용하여 코드가 향상되는 곳을 많이 볼 수 있습니다. 원본 게시물의 수정 사항을 확인하고 API에서 제기 된 제한 사항으로 인해 IReport를 사용할 수있는 능력이 무효화되었는지 확인할 수 있습니까? –

2

- 당신은 그 유형에 따라 LINQ 쿼리를 표현할 수있을 것입니다.

그렇지 않은 경우 동일한 속성을 공유하므로 C# 4에있는 경우 dynamic으로 입력 할 수 있습니다.

0

동일한 두 속성을 찾고 있는데 이름이 같은 경우 작은 인터페이스를 사용하는 것이 좋습니다.

관련 문제