将Datatable重复项与字典相结合,并遇到重复数据表数据的问题



我确实有另一个问题,在这个问题中,我认为我已经走得很好了,但我意识到Dictionary非常有用,但我需要能够真正使用我的Datatable来循环。

Dictionary正确地显示了数据,但我在编辑后的数据表上的循环清楚地显示了编辑后的和旧的数据

https://dotnetfiddle.net/6BzsYh

    DataTable table1 = new DataTable();
    table1.Columns.Add("ID", typeof (int));
    table1.Columns.Add("Weight", typeof (int));
    table1.Columns.Add("Name", typeof (string));
    table1.Columns.Add("Breed", typeof (string));
    table1.Rows.Add(23, 57, "Koko", string.Empty);
    table1.Rows.Add(44, 130, "Fido", null);
    table1.Rows.Add(54, 130, "Jack", null);
    table1.Rows.Add(44, 130, "Thad", null);
    table1.Rows.Add(64, 130, "John", null);
    table1.Rows.Add(23, 130, "Brian", null);
    table1.Rows.Add(445, 130, "James", null);
    table1.Rows.Add(64, 134, "Adam", null);
    Dictionary<int, string> dict = new Dictionary<int, string>();
    for (int i = 0; i < table1.Rows.Count; i++)
    {
        int id = Convert.ToInt32(table1.Rows[i][0]);
        if (dict.ContainsKey(id))
        {
            //comma separate the Names
            dict[id] += ", " + table1.Rows[i][2].ToString();
            // change the Name value in the table
            table1.Rows[i][2] = dict[id];
        //Console.WriteLine(dict[id]);
        }
        else
        {
            dict.Add(id, table1.Rows[i][2].ToString());
        }
    //Console.WriteLine()
    }
    foreach (DataRow eaRow in table1.Rows)
    {
        Console.WriteLine("ID=" + eaRow[0] + "  Name=" + eaRow[2]);
    }
    Console.WriteLine("nn");
    //dictionary is correct
    foreach (var item in dict)
    {
        Console.WriteLine("ID=" + item.Key + " Name=" + item.Value);
    }

如果您想要一个重复值的列表,您需要执行以下操作我还没有在一系列数据表字段上尝试过这一点,所以你需要用两个不同的字段来测试这一点——ID字段和权重字段

    DataTable table11 = new DataTable();
    table11.Columns.Add("ID", typeof(int));
    table11.Columns.Add("Weight", typeof(int));
    table11.Columns.Add("Name", typeof(string));
    table11.Columns.Add("Breed", typeof(string));
    table11.Rows.Add(23, 57, "Koko", string.Empty);
    table11.Rows.Add(44, 130, "Fido", null);
    table11.Rows.Add(54, 130, "Jack", null);
    table11.Rows.Add(44, 130, "Thad", null);
    table11.Rows.Add(64, 130, "John", null);
    table11.Rows.Add(23, 130, "Brian", null);
    table11.Rows.Add(445, 130, "James", null);
    table11.Rows.Add(64, 134, "Adam", null);
   var duplicate = table1.AsEnumerable()
       .Select(dr => dr.Field<int>("ID"))
       .GroupBy(x => x)
       .Where(g => g.Count() > 1)
       .Select(g => g.Key)
       .ToList();
   var duplicate2 = table1.AsEnumerable()
       .Select(dr => dr.Field<int>("Weight"))
       .GroupBy(x => x)
       .Where(g => g.Count() > 1)
       .Select(g => g.Key)
       .ToList();

如果您想从数据表中删除重复项,请参阅此stackoverflow发布

从数据表中删除重复项的最佳方法

相关内容

最新更新