【问题标题】:Setting the value to null using LINQ in list of list在列表列表中使用 LINQ 将值设置为 null
【发布时间】:2017-09-26 04:11:35
【问题描述】:

我有课

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;}
}

我有一个清单

List<List<ReceiptDisplayInfo>> dataSourceToBind ;

我的要求:对于每个 List ,如果 ReceiptRowCategory="Payment" ,我必须将 ReceiptItemForm,ReceiptItemCategory 的值设置为空白或 dataSourceToBind 中的 null 。

我正在使用 for 循环,但这不是最受赞赏的方法。

请协助我使用 LINQ/Lambda 表达式。

【问题讨论】:

  • 你已经尝试过什么?让我们看一些代码,还是您希望我们为您编写代码? ;)
  • @MightyBadaboom :我正在使用 for 循环,它已经嵌套。我想使用 lambda/linq

标签: c# linq lambda linq-to-objects


【解决方案1】:
 dataSourceToBind.ForEach(x =>
        {
            var innerList = x;
            innerList.ForEach(y =>
            {
                if (y.ReceiptRowCategory == "Payment")
                {
                    y.ReceiptItemFor = null;
                    y.ReceiptItemCategory = null;
                }
            });
        });

【讨论】:

    【解决方案2】:

    我想只需 2 个 ForEach 调用就足够了,这里不需要使用 LINQ。但是,由于转换逻辑相当复杂,我认为您应该将其提取为方法:

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

    然后,

    dataSourceToBind.ForEach(x => x.ForEach(SomeMethod));
    

    【讨论】:

      【解决方案3】:

      您可以使用下面的代码来实现这一点-

       ((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();
      

      【讨论】:

        猜你喜欢
        • 2017-05-31
        • 1970-01-01
        • 2022-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-17
        • 2010-09-29
        相关资源
        最近更新 更多