-4

I have a class

public class ReceiptDisplayInfo
{
public string ReceiptItemFor{get;set;}
public string ReceiptItemCategory{get;set;}
public string ReceiptItemReference{get;set;}
public string ReceiptRowCategory{get;set;}
public string ReceiptAmount{get;set;}
}

I have a list

List<List<ReceiptDisplayInfo>> dataSourceToBind ;

My requirement : For every List , if ReceiptRowCategory="Payment" , I have to set the value of ReceiptItemForm,ReceiptItemCategory to blank or null in dataSourceToBind .

I am doing using for loop but this is not the most appreciated approach.

Please assist me in doing using LINQ/Lambda Expression.

Piyush Sing
  • 45
  • 1
  • 9

3 Answers3

4
 dataSourceToBind.ForEach(x =>
        {
            var innerList = x;
            innerList.ForEach(y =>
            {
                if (y.ReceiptRowCategory == "Payment")
                {
                    y.ReceiptItemFor = null;
                    y.ReceiptItemCategory = null;
                }
            });
        });
Alok Jha
  • 353
  • 3
  • 9
0

You can use below code to achieve this-

 ((from l in list
                  where l.ReceiptItemCategory == "payment"
                  select new ReceiptDisplayInfo()
                  {
                      ReceiptItemFor = null,
                      ReceiptItemCategory = null,
                      ReceiptItemReference = l.ReceiptItemReference,
                      ReceiptRowCategory = l.ReceiptRowCategory,
                      ReceiptAmount = l.ReceiptAmount
                  }).Union(from l in list
                           where l.ReceiptItemCategory != "payment"
                           select l)).ToList();
Peeyush
  • 95
  • 8
0

I guess just 2 ForEach calls would suffice, no need to use LINQ here. However, since the transformation logic is quite complicated, I think you should extract it as a method:

private void SomeMethod(ReceiptDisplayInfo info) { // please name this appropriately
    if (info.ReceiptRowCategory == "Payment") {
        info.ReceiptItemForm = null;
        info.ReceiptItemCategory = null;
    }
}

And then,

dataSourceToBind.ForEach(x => x.ForEach(SomeMethod));
Sweeper
  • 213,210
  • 22
  • 193
  • 313