如果所有键中都有空值,请删除字典?

时间:2014-12-02 13:32:44

标签: c# list dictionary ienumerable

我有List<Dictionary<string, object>>。如果所有键都包含空值,我需要从此列表中删除字典。这是我的代码和样本。

 foreach (int rowval in rowscol)
{
   Dictionary<string, object> Data = new Dictionary<string, object>();
   foreach (Contracts.CommonDataField field in finalColumns)
   {
   var valList = record.CommonDataValues.FirstOrDefault(row => row.RowID == rowval && row.FieldName == field.FieldName);
   if (valList != null)
   {
     string value = valList.RecordFieldData;
     Data.Add(field.FieldName, value);
   }
  }
 finaldata.Add(Data);
}

我需要删除此

Sample:

包含数据的示例字典

enter image description here

3 个答案:

答案 0 :(得分:3)

如果您想稍后将其删除,为什么要将其添加到列表中?

但是,由于键是一个字符串,并且值也是一个字符串,因此应该起作用:

finaldata = finaldata
   .Where(d => d.Values.Cast<string>().Any(str => !String.IsNullOrEmpty(str)))
   .ToList();

finaldata.RemoveAll(d => d.Values.Cast<string>().All(String.IsNullOrEmpty));

如果它始终是一个字符串,我首先使用List<Dictionary<string, string>>。如果值的类型可能不同,您可以使用:

finaldata.RemoveAll(d => d.Values.All(obj => obj == null || obj.ToString() == ""));

答案 1 :(得分:1)

一个解决方案:

 foreach (int rowval in rowscol)
{
   bool hasNonNullValue = false;
   Dictionary<string, object> Data = new Dictionary<string, object>();
   foreach (Contracts.CommonDataField field in finalColumns)
   {
   var valList = record.CommonDataValues.FirstOrDefault(row => row.RowID == rowval && row.FieldName == field.FieldName);
   if (valList != null)
   {
     string value = valList.RecordFieldData;
     Data.Add(field.FieldName, value);
     if (value != null) {
        hasNonNullValue = true;
     }
   }
  }
  if (hasNonNullValue) {
    finaldata.Add(Data);
  } 
}

答案 2 :(得分:1)

foreach (int rowval in rowscol)
{
   Dictionary<string, object> Data = new Dictionary<string, object>();
   bool empty = true;
   foreach (Contracts.CommonDataField field in finalColumns)
   {
       var valList = record.CommonDataValues.FirstOrDefault(row => row.RowID == rowval && row.FieldName == field.FieldName);
       if (valList != null)
       {
           string value = valList.RecordFieldData;
           Data.Add(field.FieldName, value);
           if(!String.IsNullOrEmpty(value)) empty = false;
       }
   }
   if (!empty) finaldata.Add(Data);
}