문제

.NET 집계 기능의 간단한 예가 그렇게 작동했습니다.

string[] words = { "one", "two", "three" };
var res = words.Aggregate((current, next) => current + ", " + next);
Console.WriteLine(res);

보다 복잡한 유형을 집계하려면 어떻게 '집계'기능을 사용할 수 있습니까? 예를 들어 : '키'및 '값'과 같은 2 개의 속성이있는 클래스이며 다음과 같은 출력을 원합니다.

"MyAge: 33, MyHeight: 1.75, MyWeight:90"
도움이 되었습니까?

해결책

두 가지 옵션이 있습니다.

  1. a string 그리고 집계 :

    var values = new[] {
        new { Key = "MyAge", Value = 33.0 },
        new { Key = "MyHeight", Value = 1.75 },
        new { Key = "MyWeight", Value = 90.0 }
    };
    var res1 = values.Select(x => string.Format("{0}:{1}", x.Key, x.Value))
                    .Aggregate((current, next) => current + ", " + next);
    Console.WriteLine(res1);
    

    이것은 첫 번째를 사용하는 이점이 있습니다 string 씨앗으로 요소 (선불 없음 ",")이지만 프로세스에서 생성 된 문자열에 대한 더 많은 메모리를 소비합니다.

  2. 씨앗을 받아들이는 집계 과부하를 사용하십시오. StringBuilder:

    var res2 = values.Aggregate(new StringBuilder(),
        (current, next) => current.AppendFormat(", {0}:{1}", next.Key, next.Value),
        sb => sb.Length > 2 ? sb.Remove(0, 2).ToString() : "");
    Console.WriteLine(res2);
    

    두 번째 대표는 우리를 전환합니다 StringBuilder a string, 조건을 사용하여 시작을 트림 ",".

다른 팁

집계에는 3 개의 오버로드가 있으므로 유형이 다른 하나를 사용하여 열거하는 항목을 축적 할 수 있습니다.

시드 값 (사용자 정의 클래스)을 전달하고 씨앗을 하나의 값으로 병합하는 방법을 전달해야합니다. 예시:

MyObj[] vals = new [] { new MyObj(1,100), new MyObj(2,200), ... };
MySum result = vals.Aggregate<MyObj, MySum>(new MySum(),
    (sum, val) =>
    {
       sum.Sum1 += val.V1;
       sum.Sum2 += val.V2;
       return sum;
    }

집계 함수는 대의원 매개 변수를 허용합니다. 대의원을 변경하여 원하는 동작을 정의합니다.

var res = data.Aggregate((current, next) => current + ", " + next.Key + ": " + next.Value);

또는 string.join ()을 사용합니다.

var values = new[] {
    new { Key = "MyAge", Value = 33.0 },
    new { Key = "MyHeight", Value = 1.75 },
    new { Key = "MyWeight", Value = 90.0 }
};
var res = string.Join(", ", values.Select(item => $"{item.Key}: {item.Value}"));
Console.WriteLine(res);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top