0

So I'm trying to solve this issue, which shouldn't be too hard, but I'm stuck on it for far too long now.

This is the data I'm working with var data = "2,6;2,7;4,14;5,20";
It's a string that shows <modifierGroup>,<modifier>;<modifierGroup>,<modifier>;...

This is the model I eventually want to get my data in:

public class ModifierGroup
{
    public int Id { get; set; }
    public List<Modifier> Modifiers { get; set; }
}

public class Modifier
{
    public int Id { get; set; }
}

Right now I keep thinking I need to get my data in this format, so I can eventually push it into the model:

Key=2
    Value=6
    Value=7
    
Key=4
    Value=14
    
Key=5
    Value=20

But I could be wrong. I'd love to keep the code short. So I'd rather prevent loops in loops and doing if statements over and over. Best case scenario I get a 1 or 2-liner of code, but if it doesn't work, it doesn't work.

3
  • 1
    Create a dictionary<int, List<int>>. Split the string by ; that will give you array of string. Use ForEach Linq to process each item in the array. Each item in the array can be further split by ,. Add the item in the dictionary with the first part of the string is key (modifiergroup) and nextone is value(modifier). Commented Aug 21, 2020 at 8:12
  • Try this regular expression: var matches = Regex.Matches(data, @"(?<=(^|;))(?<key>\d+),(?<value>\d+)(;|$)").Select(m => new { key = m.Groups["key"].Value, value = m.Groups["value"].Value }) Commented Aug 21, 2020 at 8:14
  • 1
    Do you have to use that string format, or can you change it to something more structured? If you can represent the data as JSON, this all becomes very easy. :) Commented Aug 21, 2020 at 8:15

1 Answer 1

7

You could just use Split and GroupBy with a projection

var data = "2,6;2,7;4,14;5,20";
var result = data
  .Split(";")
  .Select(x => x.Split(",")
     .Select(int.Parse)
     .ToArray())
  .GroupBy(x => x[0])
  .Select(x => new ModifierGroup()
  {
     Id = x.Key, 
     Modifiers = x.Select(y => new Modifier() {Id = y[1]}).ToList()
  });
Sign up to request clarification or add additional context in comments.

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.