将文本框转换为字典

发布于 2024-12-20 07:24:47 字数 653 浏览 5 评论 0原文

我正在尝试将文本框条目转换为双精度字典。即

输入文本是:

1,63
2,31
3,78
4,83

然后我用逗号 (,) 分隔该行。

我有下面的代码 - 但 IEnumerable 不起作用。任何帮助将不胜感激!

 string input = txtInput.Text;
    List<string> list = new List<string>(
                               input.Split(new string[] { "\r\n" },
                               StringSplitOptions.RemoveEmptyEntries));

    IEnumerable<Dictionary<double, double>> dict = list.Select(row => row.Split(','))
    .Select(pair => new Dictionary<string, string>(double.Parse(pair[0]), double.Parse(pair[1])));

I'm trying to convert a textbox entry into a Dictionary of double, double. i.e.

Input text is:

1,63
2,31
3,78
4,83

I'm then splitting the row by a comma (,).

I've got the code below - but the IEnumerable isnt working. Any help would be much appreciated!!

 string input = txtInput.Text;
    List<string> list = new List<string>(
                               input.Split(new string[] { "\r\n" },
                               StringSplitOptions.RemoveEmptyEntries));

    IEnumerable<Dictionary<double, double>> dict = list.Select(row => row.Split(','))
    .Select(pair => new Dictionary<string, string>(double.Parse(pair[0]), double.Parse(pair[1])));

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁月静好 2024-12-27 07:24:47

听起来您可能想要:

var dictionary = input.Lines
                      .Select(line => line.Split(','))
                      .ToDictionary(array => double.Parse(array[0]),
                                    array => double.Parse(array[1]));

但是:

  • 这假设分割线都具有正确的位数(并且您使用的区域性使用“.”作为小数分隔符;否则您将会遇到问题)
  • 这假设每行都有可解析的 long
  • 比较 double 值是否相等(字典要求)通常是一个坏主意。您可以使用 intdecimal 代替吗?

Sounds like you probably want:

var dictionary = input.Lines
                      .Select(line => line.Split(','))
                      .ToDictionary(array => double.Parse(array[0]),
                                    array => double.Parse(array[1]));

However:

  • This assumes the split lines all have the right number of bits (and that you're using a culture which uses "." as the decimal separator; otherwise you're going to have problems)
  • This assumes each line has parsable longs in it
  • Comparing double values for equalty (required by a dictionary) is generally a bad idea. Can you use int or decimal instead?
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文