首页 > 解决方案 > 检查集合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;
        }

标签: c#

解决方案


您可以使用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();

推荐阅读