[Solved] Adding values ​to the correct subject with LINQ C# Code [closed]


You can solve your problem by grouping objects by Id1 and Id2. By the way, you sould share the test model and initialize the collection on problem definition next time ?

    internal class TestModel
    {
        public TestModel(string id1, string id2, string value)
        {
            Id1 = id1;
            Id2 = id2;
            Value = value;
        }
        public string Id1 { get; set; }
        public string Id2 { get; set; }
        public string Value { get; set; }
    }

    private void ProcessTest()
    {
        TestModel[] items = new TestModel[]
        {
            new TestModel("1","1","20.2"),
            new TestModel("1","2","18.5"),
            new TestModel("1","2","11.5"),
            new TestModel("2","1","20"),
            new TestModel("2","1","20"),
            new TestModel("2","2","50"),
            new TestModel("2","2","40"),
        };
        var result = items.GroupBy(w => new { w.Id1, w.Id2 })//group by Id1 and Id2
                .Select(w => new TestModel(w.Key.Id1, w.Key.Id2, 
                    w.Sum(q => Convert.ToDecimal(q.Value)).ToString()))//calculate the sum of group values
                .ToArray();
    }

0

solved Adding values ​to the correct subject with LINQ C# Code [closed]