728x90
반응형
728x170
▶ IEnumerable<T> 객체에서 특정 속성을 키 값으로 딕셔너리 구하기 예제
using System;
using System.Collections.Generic;
List<Product> sourceList = GetProductList(100);
Dictionary<string, Product> targetDictionary = GetDictionary<string, Product>(sourceList, "ProductName");
foreach(KeyValuePair<string, Product> keyValuePair in targetDictionary)
{
Console.WriteLine(keyValuePair.Key);
}
※ Product 클래스에 string 타입의 ProductName 속성을 가정했다.
728x90
▶ IEnumerable<T> 객체에서 특정 속성을 키 값으로 딕셔너리 구하기
using System.ComponentModel;
using System.Collections.Generic;
#region 딕셔너리 구하기 - GetDictionary(source)
/// <summary>
/// 딕셔너리 구하기
/// </summary>
/// <param name="source">소스</param>
/// <returns>딕셔너리</returns>
public static Dictionary<TValue, TItem> GetDictionary<TValue, TItem>(IEnumerable<TItem> source, string valueMember)
{
if(source == null)
{
return null;
}
if(string.IsNullOrWhiteSpace(valueMember))
{
return null;
}
bool isFirst = true;
PropertyDescriptorCollection propertyDescriptorCollection = null;
PropertyDescriptor valuePropertyDescriptor = null;
Dictionary<TValue, TItem> itemDictionary = new Dictionary<TValue, TItem>();
foreach(TItem item in source)
{
if(isFirst)
{
isFirst = false;
propertyDescriptorCollection = TypeDescriptor.GetProperties(item);
valuePropertyDescriptor = propertyDescriptorCollection[valueMember];
if(valuePropertyDescriptor == null)
{
return null;
}
}
TValue value = (TValue)valuePropertyDescriptor.GetValue(item);
if(!itemDictionary.ContainsKey(value))
{
itemDictionary.Add(value, item);
}
}
return itemDictionary;
}
#endregion
728x90
반응형
그리드형(광고전용)
'C# > Common' 카테고리의 다른 글
[C#/COMMON] 방화벽 TCP 포트 열기/닫기 (0) | 2017.07.09 |
---|---|
[C#/COMMON] 네트워크 어댑터 활성화/비활성화 하기 (0) | 2017.07.09 |
[C#/COMMON] Ping 클래스 : 인터넷 연결 여부 구하기 (0) | 2017.07.09 |
[C#/COMMON] 인터넷 연결하기/연결끊기 (0) | 2017.07.09 |
[C#/COMMON] 방화벽 인터넷 차단 규칙 추가하기/제거하기 (0) | 2017.07.08 |
[C#/COMMON] ReadOnlyCollection<T> 클래스 : 읽기 전용 컬렉션 구하기 (0) | 2017.07.03 |
[C#/COMMON] 공용체 사용하기 (0) | 2017.07.03 |
[C#/COMMON] ManagementClass 클래스 : MAC 주소 구하기 (0) | 2017.07.03 |
[C#/COMMON] 바로가기 생성하기 (0) | 2017.06.29 |
[C#/COMMON] 바로가기 생성하기 (0) | 2017.06.29 |
댓글을 달아 주세요