从文件

时间:2016-08-28 14:19:05

标签: c# arrays io tuples

我有一个文本和数字文件,需要将其导入Tuple<string, int>数组(Tuple<string, int>[] vowels = new Tuple<string, int>[81])。该文件看起来像这样

a,2,e,6,i,3,o,8,u,2,y,5

我使用的当前方法最初使用

将其导入字符串数组

string[] vowelsin = File.ReadAllText("path.txt").Split(',');

导入后,我使用

将数据转换为元组
    for (int x = 0; x < 81; x++)
        vowels[x] = Tuple.Create(vowelin[x*2], int.Parse(vowelin[(x*2) + 1]));

虽然它有效,但它有点难以阅读,在测试过程中,需要大约100毫秒才能完成。是否有任何潜在的单行,更快的方法或更可读的方法可以实现相同的目标?

2 个答案:

答案 0 :(得分:1)

string[] vowelsin = File.ReadAllText("path.txt").Split(',');
vowles = vowelsin.Zip(vowelsin.Skip(1), 
                           (a, b) => new Tuple<string, string>(a, b))
                      .Where((x, i) => i % 2 == 0)
                      .ToArray();

答案 1 :(得分:1)

您可以使用 KeyValuePair 字典代替元组。

根据这个using FILTER clause or CASE inside aggregation function元组比KeyValuePair快。您可以找到更多观点article

另一方面,字典和元组之间的比较here

好消息来到这里:

  

从C#7.0开始,引入了一个关于元组的新功能:

(string, string, string) LookupName(long id) // tuple return type
{
    ... // retrieve first, middle and last from data storage
    return (first, middle, last); // tuple literal
}

这是使用元组的新方法:(type,...,type),这意味着该方法将返回多个值(在本例中为3)。

该方法现在有效地返回三个字符串,在元组值中包含为元素。

该方法的调用者现在将收到一个元组,并可以单独访问这些元素:

var names = LookupName(id);
WriteLine($"found {names.Item1} {names.Item3}.");

可在此处找到更多信息here您会发现这些新元组相对于 System.Tuple&lt;,&gt;

的优势
相关问题