Reputation: 184
I am working an an old project which has to do with invoices.
My problem is that the previous programmer put some values in the wrong column.
To be more specific he put the total amount in column 'credit' instead of column 'charge'.
I want to fix those values andmove them to the correct column using linq but I don't know how to do it. I've searched on the internet but I couldn't find something similar.
I am using this code to get the invoices for the customer
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
}
}
}
}
Upvotes: 1
Views: 377
Reputation: 3455
As mentioned in the comments Linq is for querying and not for looping.
If you want a "cool" Foreach you could do it with 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);
}
}
Upvotes: 0
Reputation: 3810
Is the following code what you need?
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;
}
}
}
}
Upvotes: 3