【问题标题】:c# split and then make math operation [closed]c#拆分然后进行数学运算[关闭]
【发布时间】:2014-05-31 12:24:17
【问题描述】:

文件包含

Londres, 14
Berlin, 11    
New York, 9    
Tokyo, 11

程序应该读取每个字符串,删除温度(寻找数字 在逗号之后)并找到4的平均温度,写下 屏幕,4个城市温度和平均温度。

我尝试过这样的事情,它只显示城市的名称,但我需要知道平均温度。我不知道怎么做。

   string cami = "";

        FileStream fs = new FileStream(@"C:\..\..\..\..\..\..\..\ex1.txt", FileMode.Open);
        StreamReader sr = new StreamReader(fs);

        while (sr.Peek() != -1)
        {
            cami = sr.ReadLine();
            string[] s = cami.Split(',');
            Console.WriteLine("{0}", s);
        }

【问题讨论】:

  • 你问的实际问题是什么?
  • 使用正则表达式,如果卡住了就回来

标签: c# split


【解决方案1】:

试试这个:

var data =
    File
        .ReadAllLines(@"@"C:\..\..\..\..\..\..\..\ex1.txt"")
        .Select(line => line.Split(','))
        .Select(parts => new
        {
            city = parts[0],
            temperature = decimal.Parse(parts[1].Trim())
        })
        .ToArray();

Array.ForEach(data, item => Console.WriteLine(item.city));

Console.WriteLine(data.Average(item => item.temperature));

我明白了:

Londres
Berlin
New York
Tokyo
11.25

【讨论】:

    猜你喜欢
    • 2013-05-31
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 2016-01-26
    • 1970-01-01
    • 2011-12-18
    相关资源
    最近更新 更多