0

I have a List and I want to convert it to a Dictionary. I don't have any problem in converting a List to Dictionary but I want to check if the key in the Dictionary is present or not, if present I should neglect the KeyValuePair and proceed with the next string.

Here is the example.

IEnumerable<String> readlines = File.ReadAllLines("C:\Text.txt");
List<string> lines = new List<string>();
lines = readlines.ToList();
Dictionary<string, string> keyPair= new Dictionary<string, string>();         
keyPair= test.ToDictionary(s=>s.Split('=')[1], s=>s.Split('=')[0]);  
keyPair.Keys.ToList().Sort();

If the same key repeats , the lambda expression throws and exception and I want to check whether the key exists or not and proceed with converting next string to dictionary. I want to convert the dictionary back to List once the key sorting is done. Is there any way to do it with LINQ?

psubsee2003
  • 8,563
  • 8
  • 61
  • 79

2 Answers2

0

Group by your key first

See this question: Convert list to dictionary using linq and not worrying about duplicates

Something like this should work for you:

var dictionary = lines.GroupBy(s => s.Split('=')[1], x => x.Split('=')[0])
                      .ToDictionary(g => g.Key, g => g.First());

You could change the logic of the value selector to you liking

Community
  • 1
  • 1
NinjaNye
  • 7,046
  • 1
  • 32
  • 46
0

If you want the result as a list, there is no reason to put it in a dictionary.

Split each item and group on the key, sort the groups on the key, and select the value that you want from the group. If I understand you right, you want only the first value for each key:

List<string> lines = File.ReadAllLines(@"C:\Text.txt").ToList();
lines =
  lines.Select(x => x.Split('='))
  .GroupBy(a => a[0])
  .OrderBy(g => g.Key)
  .Select(g => g.Key + "=" + g.First()[1])
  .ToList();
Guffa
  • 687,336
  • 108
  • 737
  • 1,005