Необходимо добавить значение второй строки к первой, если вторая строка Стоимость = 0 - PullRequest
0 голосов
/ 17 марта 2020

У меня здесь странная ситуация. У меня есть такая структура таблицы

enter image description here

Когда стоимость равна 0, мне нужно поместить описание строки 2 вместе с описанием строки 1.

I я должен получить это в конце

enter image description here

Я пытаюсь сделать это в c#, но с треском провалился. вот где я нахожусь на

enter image description here

Ответы [ 2 ]

1 голос
/ 17 марта 2020

Ну, простой foreach должен группа пунктов _financials:

List<Financials> _financials = ...

...

List<List<Financials>> groups = new List<List<Financials>>();

foreach (Financials item in _financials) 
  if (item.cost != 0 || groups.Count <= 0) 
    groups.Add(new List<Financials>() {item})
  else  
    groups[groups.Count - 1].Add(item); 

Тогда вы можете распечатать groups out:

using System.Linq;

...

foreach (var group in groups)
  Console.WriteLine($"{string.Join(" ", group.Select(item => item.description))} {group.First().cost}");

Если вы хотите превратить groups в List<Financials>:

var compressedFinancials = groups
  .Select(group => new Financials() {
     description = string.Join(" ", group.Select(item => item.description)),
     cost        = group.First().cost,
   })
  .ToList();
1 голос
/ 17 марта 2020

работают следующие работы:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt1 = new DataTable();
            dt1.Columns.Add("Desc", typeof(string));
            dt1.Columns.Add("Cost", typeof(int));

            dt1.Rows.Add(new object[] { "Line 1", 200 });
            dt1.Rows.Add(new object[] { "Line 2", 0 });
            dt1.Rows.Add(new object[] { "Line 3", 0 });
            dt1.Rows.Add(new object[] { "Line 4", 500 });
            dt1.Rows.Add(new object[] { "Line 5", 0 });

            DataTable dt2 = dt1.Clone();

            string description = "";
            int total = 0;
            int cost = 0;
            int rowNumber = 0;
            foreach (DataRow row in dt1.AsEnumerable())
            {
                string newDescription = row.Field<string>("Desc");
                cost = row.Field<int>("Cost");

                if ((++rowNumber == 1) || (cost == 0))
                {
                    description += " " + newDescription;
                    total += cost;
                }
                else
                {
                    dt2.Rows.Add(new object[] { description, total });
                    total = cost;
                    description = newDescription;
                }
            }
            if (total != 0)
            {
                dt2.Rows.Add(new object[] { description, total });
            }


        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...