0

I have a text file and I need to put all even lines to Dictionary Key and all even lines to Dictionary Value. What is the best solution to my problem?

int count_lines = 1;
Dictionary<string, string> stroka = new Dictionary<string, string>();

foreach (string line in ReadLineFromFile(readFile))
{
    if (count_lines % 2 == 0)
    {
        stroka.Add Value
    }
    else
    { 
       stroka.Add Key
    }

    count_lines++;
}
1
  • 2
    What is the key-value correspondence? Line number 2n-1 is key and 2n is value? Commented Jun 2, 2013 at 17:39

4 Answers 4

8

Try this:

var res = File
    .ReadLines(pathToFile)
    .Select((v, i) => new {Index = i, Value = v})
    .GroupBy(p => p.Index / 2)
    .ToDictionary(g => g.First().Value, g => g.Last().Value);

The idea is to group all lines by pairs. Each group will have exactly two items - the key as the first item, and the value as the second item.

Demo on ideone.

Sign up to request clarification or add additional context in comments.

Comments

2

You probably want to do this:

var array = File.ReadAllLines(filename);
for(var i = 0; i < array.Length; i += 2)
{
    stroka.Add(array[i + 1], array[i]);
}

This reads the file in steps of two instead of every line separately.

I suppose you wanted to use these pairs: (2,1), (4,3), ... . If not, please change this code to suit your needs.

1 Comment

His own solution was streaming but your solution require to load whole file to memory before forming dictionary. Your solution require twice more memory
2

You can read line by line and add to a Dictionary

public void TextFileToDictionary()
{
    Dictionary<string, string> d = new Dictionary<string, string>();

    using (var sr = new StreamReader("txttodictionary.txt"))
    {
        string line = null;

        // while it reads a key
        while ((line = sr.ReadLine()) != null)
        {
            // add the key and whatever it 
            // can read next as the value
            d.Add(line, sr.ReadLine());
        }
    }
}

This way you will get a dictionary, and if you have odd lines, the last entry will have a null value.

Comments

0
  String fileName = @"c:\MyFile.txt";
  Dictionary<string, string> stroka = new Dictionary<string, string>();

  using (TextReader reader = new StreamReader(fileName)) {
    String key = null;
    Boolean isValue = false;

    while (reader.Peek() >= 0) {
      if (isValue)
        stroka.Add(key, reader.ReadLine());
      else
        key = reader.ReadLine();

      isValue = !isValue;
    }
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.