0

I have a stringbuilder output as (AnimalAge;Dog:20,Cat:10,Rat:5#\r\nAnimalType;Whale:Mammal,Crocodile:Reptile#\r\n)

I want to have AnimalAge as different entity and AnimalType as a different output.

How do i separate these values so that i can populate this in different textboxes\labels?

  • What about String.Split()? http://msdn.microsoft.com/en-us/library/system.string.split.aspx – Jason Mar 05 '12 at 07:41
  • String.Split works fine.. but here i have multiple characters in a single string separating different values. what i wanted to know that is there any other way by which i can have the values fetched. – user1249286 Mar 05 '12 at 07:46
  • Also using multiple splits can be used with different delimiters but I want some another way by which i can reduce LoC and increase performance. – user1249286 Mar 05 '12 at 07:47
  • String.Split() is as basic as you go - it's basically just parsing your string. You might add Regexes, and you might want to see: http://stackoverflow.com/questions/1254577/string-split-by-multiple-character-delimiter – Jason Mar 05 '12 at 07:50
  • @Jason arguably IndexOf and choosing the offset/delimiter each time is lower-level – Marc Gravell Mar 05 '12 at 08:11

1 Answers1

1

I didn't optimize the code, but it should look like

var text = new StringBuilder("AnimalAge;Dog:20,Cat:10,Rat:5#\r\nAnimalType;Whale:Mammal,Crocodile:Reptile#\r\n");

var cat = text.ToString().Split(new[] { "#\r\n" }, StringSplitOptions.RemoveEmptyEntries)
    .Select(x => x.Split(new[] { ";" }, StringSplitOptions.None))
    .Select(x => new 
    {
        Category = x[0],
        Values = x[1].Split(new[] { "," }, StringSplitOptions.None)
    })
    .Select(x => new
    {
        Category = x.Category,
        Values = x.Values.ToDictionary(y => y.Split(new[] { ":" }, StringSplitOptions.None)[0], y => y.Split(new[] { ":" }, StringSplitOptions.None)[1])
    })
    .ToList();

In the end you will get a list of Category/Values object, where Values is a Dictionary

MarkH
  • 31
  • 2