1
나는 IEnumberable>을 가지고 있으며 키 목록 만 원하지만 필요한 형식 (즉, 짧고 int가 아님)으로 캐스트합니다. 이 바인딩은 사용자 정의 제네릭 다중 선택 제어에 사용되지만 데이터베이스는 잠재적으로 '짧게'저장해야합니다.IEnumerable <KeyValuePair>에서 일반 GetOnlyKeys에 대한 확장 메서드 <int, string>>
public static IEnumerable<T> GetKeysOnly<T>(this IEnumerable<KeyValuePair<int, string>> values)
{
Dictionary<int, string> valuesDictionary = values.ToDictionary(i => i.Key, i => i.Value);
List<int> keyList = new List<int>(valuesDictionary.Keys);
// Returns 0 records cuz nothing matches
//List<T> results = keyList.OfType<T>().ToList();
// Throws exception cuz unable to cast any items
//List<T> results = keyList.Cast<T>().ToList();
// Doesn't compile - can't convert int to T here: (T)i
//List<T> results = keyList.ConvertAll<T>(delegate(int i) { return (T)i; });
throw new NotImplementedException();
}
public static IEnumerable<short> GetKeysOnly(this IEnumerable<KeyValuePair<int, string>> values)
{
Dictionary<int, string> valuesDictionary = values.ToDictionary(i => i.Key, i => i.Value);
List<int> keyList = new List<int>(valuesDictionary.Keys);
// Works but not flexable and requires extension method for each type
List<short> results = keyList.ConvertAll(i => (short)i);
return results;
}
내 일반적인 확장 방법을 사용하는 방법에 대한 조언이 있으십니까?
감사합니다.
수정을,하지만 난 내가 키를 변환 할 유형을 전달하고 싶다. GetKeysOnly –
AdventurGurl
아, 대답을 포맷하려면 1 초만주세요. 꽤 쉽습니다. – Tejs
그 코드는 저에게 오류를줍니다 : 인수 2는 'int'에서 'System.TypeCode'로 변환 할 수 없습니다. – AdventurGurl