如何使用linq将列数据移至同一行中的另一列

时间:2019-04-10 11:12:58

标签: c# linq

我正在处理一个与发票有关的旧项目。

我的问题是以前的程序员在错误的列中输入了一些值。

更具体地说,他将总额放在“贷方”列而不是“费用”列中。

我想修复这些值,并使用linq将其移至正确的列,但我不知道该怎么做。 我在互联网上进行搜索,但找不到相似的内容。

我正在使用此代码来获取客户的发票

foreach (Customer customer in CustomerList)
{
    foreach (KartelesPelaton p in customer.KartelesPelaton.OrderBy(p => p.Imerominia))
    {
        if (p.IsInvoice)
        {

            if (p.Credit.HasValue)
            {
                //Change this record data from p.Credit to p.Charge
            }
        }
    }
}

2 个答案:

答案 0 :(得分:3)

您需要以下代码吗?

foreach (Customer customer in CustomerList)
{ 
    foreach (KartelesPelaton p in customer.KartelesPelaton.OrderBy(p => p.Imerominia))
    {
        if (p.IsInvoice)
        {
            if (p.Credit.HasValue)
            {
                p.Charge = p.Credit;
                p.Credit = null;
            }
        }
    }
}

答案 1 :(得分:0)

如评论中所述,Linq用于查询而不是用于循环。

如果您想使用“酷”的Foreach,可以使用Parallel.Foreach

Parallel.ForEach(CustomerList.SelectMany(c => c.KartelesPelaton), k => { if (k.IsInvoice) k.Charge = k.Credit; k.Credit = 0; });

完整示例

public class Customer
{
    public int Id { get; set; }
    public List<KartelesPelaton> KartelesPelaton { get; set; }

    public override string ToString() => "Id " + this.Id + ":" + String.Join(", ", this.KartelesPelaton.Select(s => s));
}

public class KartelesPelaton
{
    public bool IsInvoice { get; set; }
    public int Credit { get; set; }
    public int Charge { get; set; }

    public override string ToString() => "Is " + (this.IsInvoice ? "" : "NOT ") + "Invoice! " + Credit + " - " + Charge;
}

public static void Main(string[] args)
{
    // Some example-data..
    List<Customer> CustomerList = new List<Customer>()
    {
        new Customer() { Id = 1, KartelesPelaton = new List<KartelesPelaton>() { new KartelesPelaton() { IsInvoice = false, Credit = 1 } } },
        new Customer() { Id = 2, KartelesPelaton = new List<KartelesPelaton>() { new KartelesPelaton() { IsInvoice = true, Credit = 2 }, new KartelesPelaton() { Credit = 22 } } },
        new Customer() { Id = 3, KartelesPelaton = new List<KartelesPelaton>() { new KartelesPelaton() { IsInvoice = true, Credit = 3 } } },
    };

    // Let's see what we got..
    Console.WriteLine("Before:");
    foreach (Customer c in CustomerList)
    {
        Console.WriteLine(c);
    }

    // Select items to modify (customers seem not to be important here..)
    var itemsToModify = CustomerList.SelectMany(c => c.KartelesPelaton);
    // Process the items
    Parallel.ForEach(itemsToModify, k => { if (k.IsInvoice) k.Charge = k.Credit; k.Credit = 0; });

    Console.WriteLine("After:");
    foreach (Customer c in CustomerList)
    {
        Console.WriteLine(c);
    }
}