c# - 检查集合c#中是否存在元素
问题描述
我试图阻止在 C# 中已经存在的列表中添加一个项目。下面的代码循环遍历数据表行。如您所见, rows 属于类型List<CubeReportRow>
数据表行确实包含重复项。我需要检查数据表中的 rowName 是否已经在 rows 类型的对象中List<CubeReportRow>
。请查看我在 foreach 循环中设置的条件。当我尝试按行名检查时,它说无法将字符串转换为 CubeReportRow 类型。如果我检查 if (!rows.Contains(row[0])),没有编译错误,但我不工作。如何检查它在行集合中的存在。
类 CubeReportRow
public class CubeReportRow
{
public string RowName { get; set; }
public string RowParagraph { get; set; }
public int ReportSection { get; set; }
}
C# 方法
public virtual IList<CubeReportRow> TransformResults(CubeReport report,DataTable dataTable)
{
if (dataTable.Rows.Count == 0 || dataTable.Columns.Count == 0)
return new List<CubeReportRow>();
var rows = new List<CubeReportRow>();
var columns = columnTransformer.GetColumns(dataTable);
foreach (DataRow row in dataTable.Rows)
{
var rowName = row[0].ToString();
if (!rows.Contains(rowName))
{
var values =
cubeReportValueFactory.CreateCubeReportValuesForRow(dataTable, row, rowName, columns, report);
var reportRow = new CubeReportRow(row[3].ToString(), row[2].ToString(), row[1].ToString(), values);
rows.Add(reportRow);
}
}
return rows;
}
解决方案
您可以使用Dictionary<string, CubeReportRow>
您的rows
变量并检查 key ( rowName
) 是否存在ContainsKey
:
var rows = new Dictionary<string, CubeReportRow>();
if (!rows.ContainsKey(rowName))
{
// ...
rows.Add(rowName, reportRow);
}
// ...
return rows.Values.ToList();
推荐阅读
- c++ - 调用 constexpr 函数的给定重载时触发编译时错误
- r - .$VariableName 的含义
- excel - 如何调用使用 Sample_ 生成的 excel 文件
.doc 每次都在 Windows 批处理文件中? - java - 写入 s3 时如何避免“org.apache.http.NoHttpResponseException”
- python - Qt 布局不反映组框大小变化
- php - 在zend框架中使用复杂的where条件
- android - 从 SQLite 数据库检索数据时出错
- django - Django 计数具有重复值的行
- dns - 如何设置 DNS 名称以避免更改 IP
- c# - 在 MVc5 Repo 模式中没有为此对象定义无参数构造函数