在列表列表中使用 LINQ 将值设置为 null

Posted

技术标签:

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

我有课

public class ReceiptDisplayInfo

public string ReceiptItemForget;set;
public string ReceiptItemCategoryget;set;
public string ReceiptItemReferenceget;set;
public string ReceiptRowCategoryget;set;
public string ReceiptAmountget;set;

我有一个清单

List<List<ReceiptDisplayInfo>> dataSourceToBind ;

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

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

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

【问题讨论】:

你已经尝试过什么?让我们看一些代码,还是您希望我们为您编写代码? ;) @MightyBadaboom :我正在使用 for 循环,它已经嵌套。我想使用 lambda/linq 【参考方案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();

【讨论】:

以上是关于在列表列表中使用 LINQ 将值设置为 null的主要内容,如果未能解决你的问题,请参考以下文章

Excel导入错误不能将值null插入uschool列表

使用 location.href 将值从视图传递到控制器为 null

如何将值设置为下拉列表

获取隐藏下拉列表禁用选定选项的值

如何将值列表设置为休眠查询的参数?

Linq 表未出现在 BindingSources 的数据源列表中