2012-12-03 2 views
0

나는 DateTime이라는 컬렉션이 reportLogs입니다. 이 Collection<DateTime>에서 ShortDateStringCollection<T>을 생성해야합니다. 가장 효율적인 방법은 무엇입니까?컬렉션을 다른 컬렉션 (목록 아님)으로 변환

Collection<DateTime> reportLogs = reportBL.GetReportLogs(1, null, null); 
Collection<string> logDates = new Collection<string>(); 
foreach (DateTime log in reportLogs) 
{ 
    string sentDate = log.ToShortDateString(); 
    logDates.Add(sentDate); 
} 

편집는 :

질문에 대한 Collection of string이다; List of string 아닙니다. 어떻게 문자열 컬렉션을 처리 할 수 ​​있습니까?

참조 :

  1. Using LINQ to convert List<U> to List<T>
  2. LINQ convert DateTime to string
  3. Convert a datetime in a subcollection of collection and use it in LINQ to SQL
  4. convert Collection<MyType> to Collection<Object> 그냥 IEnumerable<string> 행복 경우

답변

3

:

IEnumerable<string> logDates = reportBL.GetReportLogs(1, null, null) 
             .Select(d => d.ToShortDateString()); 

당신은 하나 더 호출로 쉽게 List<string>

List<string> logDates = reportBL.GetReportLogs(1, null, null) 
             .Select(d => d.ToShortDateString()) 
             .ToList(); 

편집이를 돌 수 있었다 : 당신은 정말 다음 클래스는 a constructor which takes IList<T> 그래서 다음이 작동하고있다 Collection<T>으로 개체를해야하는 경우 :

Collection<string> logDates = new Collection(reportBL.GetReportLogs(1, null, null) 
             .Select(d => d.ToShortDateString()) 
             .ToList()); 
+1

로 변환 // ShortDateString

를 변환; '문자열 목록'에 관한 것이 아닙니다. '문자열 모음'을 어떻게 처리 할 수 ​​있습니까? – Lijo

+0

@Lijo - ['List '는'ICollection '을 상속합니다. (http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx) - 이것은'List '** IS ** a Collection을 의미합니다. ! – Jamiec

+0

@Lijo - 또한'Collection '에는'IList '을 사용하는 생성자가 있습니다. 그래서 위의 결과에 대한 목록을 항상 새 Collection으로 전달할 수 있습니다. 이것으로 답변을 업데이트하겠습니다. – Jamiec

0
var logDates= reportLogs.Select(d => d.ToShortDateString()); 

선택적으로 당신은 .ToList()

+1

'logDates'는 소스가 아닌 대상이었습니다. – Jamiec

+0

고마워, 나는 그것을 고쳤다. – Rik

0
//Create a collection of DateTime 

날짜 시간 OBJ = 새로운 날짜 시간 (2013,5,5)를 추가 할 수 있습니다;

List<DateTime>lstOfDateTime = new List<DateTime>() 
{ 
    obj,obj.AddDays(1),obj.AddDays(2) 


}; 

사용 List 클래스 convertAll 방법은 ShortDateString

질문은 '문자열 컬렉션'에 관한 것입니다
Lis<string> toShortDateString = lstOfDateTime.ConvertAll(p=>p.ToShortDateString()); 
관련 문제