Convert List<string> to List<object> in C# - c#

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 ?

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();

foreach(var rawString in rawData){
var split = rawString.Split(";");
processedData.Add(new Data(){
instruments = split[0],
positions = split[1]
});
}

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));
}
}

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; }
}

Related

How to convert list item to multidimensional array in c#?

I have a single list of data like
List 0 index Contains : BlockId = 438001,DistrictId = 438,TownId = 0,UserId = 1077
UserTypeId = 4,VillageId = 238047,ZoneId = 1018
List 1 index contains : BlockId = 438001,DistrictId = 438,TownId = 0,UserId = 1077,UserTypeId = 4,VillageId = 238048,ZoneId = 1018
List 2 index contains : BlockId = 438002,DistrictId = 438,TownId = 0,UserId = 1077,UserTypeId = 4,VillageId = 238138,ZoneId = 1018
And now I want to create a multidimensional array according to that like
public List<int>[][] arrayList{get;set;}
I need to convert list data to multidimensional array list like
[0]
[0] -> Count 1 -> 438001 --> Showing blockId
[1]-> Count 3 -> 238047,238048 --> showing villageId
[1]
[0]->count 1 -> 438002
[1]->count 2 -> 238138
[2]->count 3-> 0 --> showing townId
var data = user.getUserRolebyUserId(userId);
var blkList = data.GroupBy(x => x.BlockId);
List<int>[][] lst;
foreach (var item in data.GroupBy(x => x.BlockId))
{
List<int>[][] array = [item.Key,item.Select(x => x.VillageId).ToList(), item.Select(q => q.TownId)];
}
I am trying to applying this but it's showing me error for Invalid Expression.
So How can I convert list into multidimensional array ?
Use a Dictionary :
class Program
{
static void Main(string[] args)
{
List<Location> locations = new List<Location>() {
new Location() { BlockId = 438001,DistrictId = 438,TownId = 0,UserId = 1077, UserTypeId = 4,VillageId = 238047,ZoneId = 1018 },
new Location() { BlockId = 438001,DistrictId = 438,TownId = 0,UserId = 1077,UserTypeId = 4,VillageId = 238048,ZoneId = 1018},
new Location() { BlockId = 438002,DistrictId = 438,TownId = 0,UserId = 1077,UserTypeId = 4,VillageId = 238138,ZoneId = 1018 }
};
Dictionary<int, List<int>> dict = locations
.GroupBy(x => x.BlockId, y => y.Items)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
}
}
public class Location
{
public int BlockId { get; set; }
public int DistrictId { get; set; }
public int TownId { get; set; }
public int UserId { get; set; }
public int UserTypeId { get; set; }
public int VillageId { get; set; }
public int ZoneId { get; set; }
public List<int> Items {
get { return new List<int> { BlockId, DistrictId, TownId, UserId, UserTypeId, VillageId, ZoneId }; }
set {;}
}
}

How to convert a list to JSON in C#?

I have a City_State list:
City_State[0].Range="\"city\":\"REDMOND\",\"state\":\"AK\"";
City_State[1].Range="\"city\":\"Alex City\",\"state\":\"
How to convert it into json like below:
var _pairs = new
{
criteria = new { cities = new[] { new { city = "REDMOND", state = "WA" },
new { city = "Alex City", state = "AL" } }
} ;
I tried the code below, but it does not work:
var _pairs = new { criteria = new { cities = new[] { _paged_City_State.ToArray() } } };
If you had these classes:
public class CityStateRaw
{
public string Range { get; set; }
}
public class CityState
{
public string City { get; set; }
public string State { get; set; }
}
The following code would work:
var ranges = new[]
{
new CityStateRaw { Range = "{\"city\":\"REDMOND\",\"state\":\"AK\"}" },
new CityStateRaw { Range = "{\"city\":\"Alex City\",\"state\":\"foo\"}" },
};
var list = ranges
.Select(raw => JsonConvert.DeserializeObject<CityState>(raw.Range))
.ToList();
But if this doesn't match your expectations you should be more concrete about what your exact input and the expected output should be.

How to get specific parts of string and assign them to variables in c#?

passing a string like this to the code behind:
0,-1|1,-1|2,-1|3,-1|4,-1|5,-1|6,-1|7,-1|8,-1
I need to be able to asign the values before and after the "," symbol per each "|" symbol that exits in the string, into separated variables, "line" for first value (before the ",") and "group" for the next one (after the ",").
Right now I'm trying with this, but I'm having some issues with converting from string[] to string.
public static string GuardarGrupos(string parametro){
var data = parametro.Split(Convert.ToChar("|"));
var datos = "";
string[] linea;
var grupo = "";
//Iterate through each of the letters
foreach (var check in data)
{
datos = data[0];
linea = data[0].Split(Convert.ToChar(","));
}
return linea;
}
Any Idea how can I achieve this?
Make a class or struct to hold your values:
public class DataObject
{
public string X {get; set;}
public string Y {get; set;}
}
Return a List<T> of type DataObject
public static List<DataObject> GuardarGrupos(string parametro){
//List to return
List<DataObject> returnList = new List<DataObject>();
//Split the string on pipe to get each set of values
var data = parametro.Split('|'); //No need to do a convert.char(),
//String.Split has an overload that takes a character, use single quotes for character
//Iterate through each of the letters
foreach (var check in data)
{
//Split on comma to get the individual values
string[] values = check.Split(',');
DataObject do = new DataObject()
{
X = values[0];
Y = values[1];
};
returnList.Add(do);
}
return returnList;
}
Once you have the List<DataObject>, you can form line and group using linq and string.Join:
List<DataObject> myList = GuardarGrupos("0,-1|1,-1|2,-1|3,-1|4,-1|5,-1|6,-1|7,-1|8,-1");
string line = string.Join(",", myList.Select(x => x.X);
string group = string.Join(",", myList.Select(y => y.Y);
Instead of using local variables , create a Class that stores your retrieved values. then in the main you could handle/manipulate those values as required.
public class MyData
{
public string Datos { get; set; }
public string Linea { get; set; }
public string Grupo { get; set; }
}
public static List<MyData> myFunction(string parametro)
{
List<MyData> result = new List<MyData>();
var data = parametro.Split(Convert.ToChar("|"));
foreach (var check in data)
{
MyData temp = new MyData();
var line = check.Split(',');
temp.Datos = line[0];
temp.Linea = line[1];
temp.Grupo = check;
result.Add(temp);
}
return result;
}
static void Main(string[] args)
{
var t = myFunction("0,-1|1,-1|2,-1|3,-1|4,-1|5,-1|6,-1|7,-1|8,-1");
}
Here is a robust solution that's just a simple iteration over a string.
void Main()
{
var xs = "0,-1|1,-1|2,-1|3,-1|4,-1|5,-1|6,-1|7,-1|8,-1";
var stack = new Stack<Pair>();
stack.Push(new Pair());
foreach(var x in xs)
if(x == '|')
stack.Push(new UserQuery.Pair());
else
stack.Peek().Accept(x);
foreach (var x in stack.Reverse())
Console.WriteLine(x);
}
sealed class Pair
{
Action<char> _Accept;
readonly List<char> Line = new List<char>();
readonly List<char> Group = new List<char>();
public Pair()
{
_Accept = x => Line.Add(x);
}
public void Accept(char c)
{
if(c == ',')
_Accept = x => Group.Add(x);
else
_Accept(c);
}
public override string ToString()
{
return "Line:" + new string(Line.ToArray()) + " Group:" + new string(Group.ToArray());
}
}

Converting an array to object

I have 2 types of string: Mer and Spl
// Example
string testMer = "321|READY|MER";
string testSpl = "321|READY|SPL";
Then I will split them:
var splitMer = testMer.Split('|');
var splitSpl = testSpl.Split('|');
I have an object to save them
public class TestObject
{
public int id { get; set; }
public string status { get; set; }
public string type { get; set; }
}
Question: How to convert the Array into the TestObject?
var converted = new TestObject
{
id = int.Parse(splitMer[0]),
status = splitMer[1],
type = splitMer[2]
};
You will need to add some error checking.
var values = new List<string> { "321|READY|MER", "321|READY|SPL" };
var result = values.Select(x =>
{
var parts = x.Split(new [] {'|' },StringSplitOptions.RemoveEmptyEntries);
return new TestObject
{
id = Convert.ToInt32(parts[0]),
status = parts[1],
type = parts[2]
};
}).ToArray();
You just need to use object initializers and set your properties.By the way instead of storing each value into seperate variables, use a List.Then you can get your result with LINQ easily.
var splitMer = testMer.Split('|');
var testObj = new TestObject();
testObj.Id = Int32.Parse(splitMer[0]);
testObj.Status = splitMer[1];
testObj.type = splitMer[2];
How about adding a Constructor to your Class that takes a String as a Parameter. Something like this.
public class TestObject
{
public int id { get; set; }
public string status { get; set; }
public string type { get; set; }
public TestObject(string value)
{
var valueSplit = value.Split('|');
id = int.Parse(valueSplit[0]);
status = valueSplit[1];
type = valueSplit[2];
}
}
Usage:
TestObject tst1 = new TestObject(testMer);
TestObject tst2 = new TestObject(testSpl);

Place List<T> values in two arrays

I have the class:
public class DataModel {
public int X { get; set; }
public int Y { get; set; }
}
And the following list:
var data = new List<DataModel>();
data = service.GetData();
I need to change the List to a List:
public class NewDataModel {
public int[] XValues { get; set; }
public int[] YValues { get; set; }
}
So XValues are all the X Values in the original list ... The same with YValues.
How can I do this with Linq?
Thank You,
Miguel
You are expected to post your best try.
var newList = new NewDataModel {
XValues = data.Select(dm => dm.X).ToArray(),
YValues = data.Select(dm => dm.Y).ToArray() };
Untested, but something like this:
var newDataModel = new NewDataModel();
newDataModel.XValues = data.Select(d => d.X).ToArray();
newDataModel.YValues = data.Select(d => d.Y).ToArray();
You should use Aggregate to loop it just once:
newDataModel = data.Select((x,i)=>new{ x, i})
.Aggregate(new NewDataModel(){XValues = new int[data.Count],
YValues = new int[data.Count]},
(a,b)=> {
a.XValues[b.i] = b.x.X;
a.YValues[b.i] = b.x.Y;
return a;
});

Categories

Resources