당신은 * 그럼 당신은 단순히
var mRes = dlookups.Select(x => new Results {
Name= x.Key,
TotalValue = mObjs.Sum(x.Value)
}).ToList();
업데이트 BEGIN 할 수
var lookups = new Dictionary<string,Func<Maths,int>> {
{"M1", x => x.M1 },
{"M2", x => x.M2 },
{"M3", x => x.M3 },
{"M4", x => x.M4 },
{"M5", x => x.M5 },
};
을 선택 이름과 필드를 모두 나열하는 사전 선택 목록을 사용할 수 있습니다
코멘트에 대한 응답으로
람다 식은 소스 클래스에서 int까지의 함수입니다. 예를
class Sub1 {
string M3 {get;set;}
int M4 {get;set;}
}
class Math2 {
string Name {get;set;}
string M1 {get;set;}
string M2 {get;set;}
Sub1 Sub {get;set;}
}
var lookups = new Dictionary<string,Func<Math2,int>> {
{ "M1", x => int.Parse(x.M1) },
{ "M2", x => int.Parse(x.M2) },
{ "M3", x => int.Parse(x.Sub.M3) },
{ "M4", x => int.Parse(x.Sub.M4} }
};
아니면 체크인 약간의 오류를 넣어하려는 경우, 당신이 사용하는 기능이나 중 하나가 코드를 포함 할 수 있습니다 들어
. 당신이 더 당신이 조회 사전을 구축하는 반사를 사용할 수 있습니다 가고 싶은 경우
int GetInt(string source) {
if (source == null) return 0;
int result;
return int.TryParse(source, out result) ? result : 0;
}
var lookups = new Dictionary<string,Func<Math2,int>> {
{ "M1", x => {
int result;
return x == null ? 0 : (int.TryParse(x,out result) ? result : 0);
},
{ "M2", x => GetInt(x) },
{ "M3", x => x.Sub == null ? 0 : GetInt(x.Sub.M3) },
{ "M4", x => x.Sub == null ? 0 : x.Sub.M4}
};
END는
업데이트되었습니다.
다음은 클래스의 모든 Integer 속성에 대한 조회를 생성하는 도우미 함수입니다.
public Dictionary<string,Func<T,int>> GenerateLookups<T>() where T: class {
// This just looks for int properties, you could add your own filter
var properties = typeof(T).GetProperties().Where(pi => pi.PropertyType == typeof(int));
var parameter = Expression.Parameter(typeof(T));
return properties.Select(x => new {
Key = x.Name,
Value = Expression.Lambda<Func<T,int>>(Expression.Property(parameter,x),parameter).Compile()
}).ToDictionary (x => x.Key, x => x.Value);
}
지금 당신은 다만 할 수 있습니다 당신은 고용해야 할 수도 있습니다,
mRes.Add(new Results() { Name = "M1", TotalValue = mObjs.Sum(x => x.M1) });
프로그래밍 모든 클래스의 속성을 반복하려면 :
var mRes=GenerateLookups<Maths>().Select(x => new Results
{
Name = x.Key,
TotalValue = mObjs.Sum(x.Value)
}).ToList();
이걸 시도해 주셔서 감사합니다. 내가 다시 돌아올 께 – mmssaann
절대적으로 똑똑합니다 .. 고마워 .. 많이 .. – mmssaann
에 직면 해 있습니다. 다른 클래스 포인트는 문자열 변수에 저장됩니다. 해당 문자열 속성을 int로 변환하려면 어떻게해야합니까? – mmssaann