0

I have a list of string that looks something like this:

var rawData = new List<string>(){ "EUR/USD;123" , "EUR/GBP;321", "BTC/USD;2321"};

I have the following structure:

public class Data
{
    public string instrument { get; set; }
    public string positions { get; set; }
}

My goal is to have a list of the string data, splited on the ';' char and converted to a list of objects.

var processedData = new List<Data>();

// processedData[0] ( instrument = EUR/USD, positions = 123 )
// processedData[1] ( instrument = EUR/GBP, positions = 321)
// processedData[2] ( instrument = BTC/USD, positions = 2321)

Do you have any idea how can I do this ?

1
  • 2
    So what happened when you tried to split the entries? Commented Apr 18, 2022 at 8:57

4 Answers 4

2

You can try Linq and query rawData:

var processedData = rawData
  .Select(item => item.Split(';'))
  .Select(items => new Data() {
     instrument = items[0],
     positions  = items[1]
   })
  .ToList(); 
Sign up to request clarification or add additional context in comments.

2 Comments

you can do in one select
@Power Mouse: Yes, it can be done in one Select, I've implemented it with two Select in order to have more readable (IMHO) code.
0
foreach(var rawString in rawData){
  var split = rawString.Split(";");

  processedData.Add(new Data(){ 
    instruments = split[0],
    positions = split[1]
  });
}

1 Comment

Your answer could be improved by adding more information on what the code does and how it helps the OP.
0

You can try this code below

        private static void TestFunc()
    {
        var rawData = new List<string>() { "EUR/USD;123", "EUR/GBP;321", "BTC/USD;2321" };
        var processedData = new List<Data1>();

        foreach (var item in rawData)
        {
            var ins = item.Split(";")[0];
            var pos = item.Split(";")[1];
            processedData.Add(new Data1(ins, pos));
        }
    }

Comments

0

you can use linq

void Main()
{
    var rawData = new List<string>() { "EUR/USD;123", "EUR/GBP;321", "BTC/USD;2321" };

    rawData.Select(s => 
            new Data() {instrument= s.Split(";")[0],positions = (s.Split(";").Count() > 1) ? s.Split(";")[1] : null})
        .ToList().Dump();

}

public class Data
{
    public string instrument { get; set; }
    public string positions { get; set; }
}

enter image description here

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.