How can I get the current totals of integer values ​​from list ()?

The list has an object that has the following properties:

public class PropertyDetails
{

 public int Sequence { get; set; }

 public int Length { get; set; }

 public string Type { get; set; }

 public int Index { get; set; }

}

The list will be sorted. Sequence.

The list has object values ​​as follows:

Sequence = 1 Length = 20 Type = "" Index = 0

Sequence = 2 Length = 8 Type = "" Index = 0

Sequence = 3 Length = 6 Type = "" Index = 0

Sequence = 4 Length = 20 Type = "" Index = 0

Sequence = 5 Length = 8 Type = "" Index = 0

I need a Linq query that will give me List as result

Sequence = 1 Length = 20 Type = "" Index = 20

Sequence = 2 Length = 8 Type = "" Index = 28

Sequence = 3 Length = 6 Type = "" Index = 34

= 4 = 20 = "" = 54

= 5 = 8 = "" = 62

, .

+3
3

, , , Jon . , , LINQ . , LINQ-.

:

var sum = 0;
foreach (var p in list) {
  sum += p.Length;
  p.Index = sum;
}

LINQ - . , , , .

+9

LINQ, - . , .

, . - :

public static IEnumerable<TResult> Scan<TSource, TResult>(
    this IEnumerable<TSource> source,
    TResult seed,
    Func<TResult, TSource, TResult> func)
{
    TResult current = seed;
    // TODO: Argument validation
    foreach (TSource item in source)
    {
        current = func(current, item);
        yield return current;
    }
}

:

var query = list.Scan(new PropertyDetails(),
                      (current, item) => new PropertyDetails { 
                           Sequence = item.Sequence,
                           Length = item.Length,
                           Index = current.Index + item.Length
                      });

EDIT: , , Reactive Extensions System.Interactive.

+3

Maybe something like this (this is not very readable):

var newList = list.Select(x =>
                        new PropertyDetails()
                        {
                            Type = x.Type,
                            Length = x.Length,
                            Sequence = x.Sequence,
                            Index = list.Take(x.Sequence).Select(y => y.Length).Aggregate((a, b) => a + b)
                        }
);
-2
source

Source: https://habr.com/ru/post/1786133/


All Articles