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

问题描述 投票:1回答:2

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

我的问题是前一个程序员在错误的列中放了一些值。

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

我想修复这些值,并使用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
            }
        }
    }
}
c# linq
2个回答
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;
            }
        }
    }
}

0
投票

正如评论中所提到的,Linq用于查询而不是用于循环。

如果你想要一个“酷”的Foreach,你可以用Parallel.Foreach做到:

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

Full example

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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.