【问题标题】:Duplicates and counting them in List重复并在列表中计数
【发布时间】:2018-03-19 21:08:27
【问题描述】:

这是我需要编辑的部分代码:

private static void SaveMetalToFile(List<Ring> rings)
{
    using (StreamWriter writer = new StreamWriter(@"Metalai.txt"))
    {
        writer.WriteLine("|Metalai |Kiekis|");
        string message = String.Empty;

        var ringDataList = rings.GroupBy(r => r.Metalas).Select(x => new { Ring = x.FirstOrDefault(), Count = x.Count() }).ToList();

        foreach (var item in ringDataList)
        {
            message = "|" + item.Ring.Metalas + "|" + item.Count + "|";
            writer.WriteLine("{0}; {1}", ring.Metalas, message);
        }
    }
}

应该避免在 Metalai.txt 文件中放置重复项,但还要计算有多少个重复项。我已经做了大约 3 种方法,我的老师说即使它有效,它也很糟糕。他说我必须使用2个变量 (writer.WriteLine("{0}; {1}", ring.Metalas, message))

但问题是我无法让它工作。他说我不能在这个列表中做任何数学运算。应该有2个方法/功能。第一个应该只读取金属数据并区分它,第二个应该计算重复项。无论我如何尝试,我都无法让它工作。

message = "|" + item.Ring.Metalas + "|" + item.Count + "|"; 是错误的,因为它使用数学(加法)。你们能帮帮我吗?

【问题讨论】:

  • 那不是加法,那是字符串连接。如果您担心使用符号 +,可以改用 string.Concat。虽然注意=也是一个数学符号..
  • The first one should read only metal data and distinct it and the second one should count the duplicates. 如果第一种方法使列表不同,则不存在重复项。 Enumerable.Distinct 用于删除重复项。

标签: c# list duplicates


【解决方案1】:

您可以执行以下操作。有很多方法可以做到这一点,但我总是喜欢使用字典或哈希集来执行您所要求的任务。至于您的打印,我认为您的老师是说您可以在 string.Format(...); 中进行所有格式设置;

    private static void SaveMetalToFile(List<Ring> rings)
    {
        Dictionary<string, int> finalCollection = new Dictionary<string, int>();
        foreach(Ring item in rings)
        {
            if(finalCollection.ContainsKey(item.Metalas))
            {
                finalCollection[item.Metalas]++;//incement duplicate count
            }
            else
            {
                finalCollection.Add(item.Metalas, 1);//add if not exist with count of 1
            }
        }

        using(StreamWriter writer = new StreamWriter(@"Metalai.txt"))
        {
            writer.WriteLine("|Metalai |Kiekis|");
            foreach(var item in finalCollection)
            {
                writer.WriteLine("{0};|{0}|{1}|", item.Key, item.Value);
            }
        }
    }

【讨论】:

  • 未处理异常:System.InvalidCastException:无法将“Grouping[System.String,_23LBUzduotis.Ring]”类型的对象转换为“_23LBUzduotis.Ring”类型。在 G:\New 文件夹\23LBUzduotis\Program.cs: _23LBUzduotis.Program.Main(String[] args) 中 G:\New 文件夹\23LBUzduotis\Program 中的 _23LBUzduotis.Program.SaveMetalToFile(List`1 个环) 中的第 67 行。 cs:第 19 行
  • 它不喜欢这一行:67: foreach (Ring item in ring.GroupBy(r => r.Metalas).ToList())
  • 很抱歉。只需在 foreach 循环中使用环就是您需要做的。
  • 你确定吗,我刚刚运行了这段代码,它在下面给出了一个文本输出。这篇文章中的代码是最新的。
  • |Metalai |Kiekis|第一;|第一|2|第二;|第二|2|第三;|第三|2|第四;|第四|1|
猜你喜欢
  • 1970-01-01
  • 2022-08-09
  • 2022-11-13
  • 2023-03-14
  • 1970-01-01
  • 2020-08-12
  • 2022-01-20
  • 2019-02-04
  • 2018-09-04
相关资源
最近更新 更多