0

I have a file filled with text and numbers and need to import it into a Tuple<string, int> array (Tuple<string, int>[] vowels = new Tuple<string, int>[81]). The file looks something like this

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

The current method I use initially imports it into a string array using

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

After importing, I turn the data into Tuples using

    for (int x = 0; x < 81; x++)
        vowels[x] = Tuple.Create(vowelin[x*2], int.Parse(vowelin[(x*2) + 1]));

While it works, it's a bit hard to read and during tests, takes around 100ms to complete. Are there any potential one-liners, faster methods, or more readable methods that could pull off the same thing?

CocoaMix86
  • 69
  • 1
  • 9
  • Using String.Split is a big waste of performance. It can be written way faster by iterating over the content charachterwise and act accordingly. – CSharpie Aug 28 '16 at 14:39

2 Answers2

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();
serhiyb
  • 4,753
  • 2
  • 15
  • 24
  • While code-only answers are not forbidden, please understand that this is a Q&A community, rather than a crowd-sourcing one, and that, usually, if the OP understood the code being posted as an answer, he/she would have come up with a similar solution on his/her own, and wouldn't have posted a question in the first place. The same principle also applies further to any future readers who might be unfamiliar with the code being presented. As such, please provide context to your answer and/or code by explaining how and/or why it works. – CosmicGiant Aug 28 '16 at 17:35
1

You can use a KeyValuePair or a Dictionary instead of Tuples.

According to this article Tuples are faster than KeyValuePair. You can find more points of view here.

On the other hand, a comparison between Dictionaries and Tuples were made here.

The good news comes here:

As of C#7.0 a new feature about Tuples was introduced:

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

This is the new way for using tuples: (type, ..., type) and it means that the method will return more than one value(three in this case).

The method now effectively returns three strings, wrapped up as elements in a tuple value.

The caller of the method will now receive a tuple, and can access the elements individually:

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

Further information can be found here What is new in C# 7.0 There you will find the advantages of these new Tuples over System.Tuple<,>

Community
  • 1
  • 1
Luis Teijon
  • 4,769
  • 7
  • 36
  • 57