Datatable to array and then to a Textbox - c#

I have a datatable with only one column and rows with just some integers. I would like to transition them into a array so I can display them in a textbox

You can use Linq and String.Join:
int[] nums = table.AsEnumerable().Select(r => r.Field<int>(0)).ToArray();
TextBoxNums.Text = string.Join(",", nums);
If you want to split them by a new line:
string[] nums = table.AsEnumerable().Select(r => r.Field<int>(0).ToString()).ToArray();
TextBoxNums.Lines = nums;

Related

Cut last character from string which was earlier splitted by char

I want to order list with string names by name included in brackes.
List<string> result = new List<string>();
list.ForEach(elem => result.Add(elem.Value));
result.Add(item);
result = result.OrderBy(o=>o.Split(';')[0].Substring(0, o.Length - 1).Split('(')[1]).ToList();
Example: 2-osobowy(Agrawka);Śniadanie+Obiadokolacja
I want to extract this name Agrawka
How to change instruction Substring(0, o.Length - 1)to cut last char from splitted string in orderby instruction?
If I right understood you want extract values in the brackets and sort input' list by that values. So code below sorts your data and extracts value to additional list:
List<string> resultList = new List<string>() { "2-osobowy(Bgrawka);Śniadanie+Obiadokolacja", "2-osobowy(Agrawka);Śniadanie+Obiadokolacja" };
string tempStr = null;
var extractedStr = new List<String>();
resultList = resultList.OrderBy(o =>
{
var extract = (tempStr = o.Split(';')[0].Split('(')[1]).Substring(0, tempStr.Length - 1);
extractedStr.Add(extract);
return extract;
}).ToList();
If you want only sort input data just simplify the lambda:
resultList = resultList.OrderBy(o => (tempStr = o.Split(';')[0].Split('(')[1]).Substring(0, tempStr.Length - 1)).ToList();

split string array c#

So I have multiple arrays of strings. Within each array I have a string which uses '|' as a separator. What I need is to create a string with the first elements of the array up until the '|'.
So in the example I need 6485,6486,6487,6509,6510,6511,6533,6534,6535,|
Use String.Split() to split the original strings, then store the first ones in a separate array, then use String.Join() to concatenate them
string[] tempStrings = new string[stringArray.Length];
for(int i = 0; i < stringArray.Length; i++)
{
tempStrings[i] = stringArray[i].Split(#"|")[0];
}
string result = String.Join(",", tempStrings);
Using System.Linq :
string[] temp = new string[] { "1,2,3|4,5,6|7,8,9", "10,11,12|13,14,15", "16,17,18"};
var result = String.Join(",", temp.Select(x => x.Split('|').FirstOrDefault())
.ToList());
With null and empty values :
string[] temp = new string[] { "1,2,3|4,5,6|7,8,9", "10,11,12|13,14,15", "16,17,18", "", null };
var result = String.Join(",", temp.Select(x => x?.Split('|').FirstOrDefault())
.Where(x => !string.IsNullOrWhiteSpace(x))
.ToList());

Splitting an array into 2D or two arrays

I have a text file that I am reading to pull out register values and what they contain.
2 lines from the array pulled out is: (full list is about 700)
0x0003 = 0x0069
0x0007 = 0x0078
I would like to split these into two arrays or one 2-dimensional array, whatever is best(I am new to using arrays)
My goal is to search the array for example for register 3, find the index then extract the information from the 2nd arrays corresponding index.
Here is my code so far ,
List<string> registerFullList1 = new List<string>();
for (int i = 0; i < 2000; i++)
{
string[] importStringArray1 = new string[2000];
importStringArray1[i] = importStringArray1[i] + objReader.ReadLine() + "\r\n";
//code to extract register info from string array
string listsplit1 = Regex.Match(importStringArray1[i], #"(?<= 0x)[0-9A-Fa-z\s\=]{13}").Value;
if (listsplit1.Contains("0x")) //code to add to list only registers and ignore empty lines
{
registerFullList1.Add(Convert.ToString(listsplit1));
}
}
int[] index = new int[2000]; // is there a way here that I don't have to assign 0,1,2,3 to each assignment?
index[0] = registerFullList1.FindIndex(x => x.StartsWith("0003 ="));
Register3.Text = Regex.Match(registerFullList1[index[0]], #"(?<= 0x)[0-9A-F]{4}").Value;
index[1] = registerFullList1.FindIndex(x => x.StartsWith("0007 ="));
Register7.Text = Regex.Match(registerFullList1[index[1]], #"(?<= 0x)[0-9A-F]{4}").Value;
This all works no problem and I am displaying the register content in text boxes. But I would like two arrays so it is more proper, one with register numbers and one with content. I cant figure it out, any help would be appreciated.
UPDATE
final code after reading answers,
List<string> registerNumberList = new List<string>();
List<string> registerContentList = new List<string>();
List<string> registerFullList = new List<string>();
for (int i = 0; i < 2000; i++)
{
string[] importStringArray1 = new string[2000];
importStringArray1[i] = importStringArray1[i] + objReader.ReadLine() + "\r\n";
string listsplit1 = Regex.Match(importStringArray1[i], #"(?<= 0x)[0-9A-Fa-z\s\=]{13}").Value; // #"(?<== 0x)[0-9A-F]{4}"
string listsplit2 = Regex.Match(importStringArray1[i], #"(?<= 0x)[0-9A-Fa-z\s\=]{4}").Value;// pulls out the register number from original array
string listsplit3= Regex.Match(importStringArray1[i], #"(?<== 0x)[0-9A-Fa-z\s\=]{4}").Value;//pulls out register content from original array
if (listsplit1.Contains("0x"))
{
registerNumberList.Add(Convert.ToString(listsplit3));//makes a list with register numbers
registerContentList.Add(Convert.ToString(listsplit2) );//makes a list with register content
registerFullList.Add(Convert.ToString(listsplit2) + "=" + Convert.ToString(listsplit3));//the full list
}
}
Dictionary <string, string> registers = registerFullList.Select(line => line.Split('=')
.ToArray())
.ToDictionary(items => items[0], items => items[1]); //joins the register numbers and content into a dictionary with just 4 decimal values for each
list1.Text = String.Join("\r\n", registerFullList);
list2.Text = registers["0010"]; // pulls out register info
Thanks guys
I suggest using Linq:
If you insist on the array:
int[][] result = File
.ReadLines(#"C:\myFile.txt")
.Select(line => line
.Split('=')
.Select(item => Convert.ToInt32(item, 16))
.ToArray())
.ToArray();
In case first index is unique one (and thus can serve as a key) you can materialize the data as a dictionary:
Dictionary<int, int> result = File
.ReadLines(#"C:\myFile.txt")
.Select(line => line
.Split('=')
.Select(item => Convert.ToInt32(item, 16))
.ToArray())
.ToDictionary(items => items[0], items => items[1]);
...
// value == 0x0078 (120)
int value = result[0x0007];
Try using a dictionary :
Dictionary<string, string> registersKeyValue = new Dictionary<string, string>();
string content = registersKeyValue
.Where(keyValuePair => keyValuePair.Key == "0x0003")
.FirstOrDefault()
.Value;

Splitting text and converting linq

I have a string array and want to convert it to double array with LINQ. I don't want to use foreach loops.
var texts = new List<string>
{"-87.98 65", "-86.98 75", "-97.98 78", "-81.98 65"}
To:
var numerics = new List<IEnumerable<double>>
{
new List<double>{-87.98, 65},
new List<double>{86.98, 75},
new List<double>{-97.98 78},
new List<double>{-81.98 65}
}
Is there any short way with LINQ?
You could use this:
var doubles = texts.Select(x => x.Split()
.Select(y => double.Parse(y, CultureInfo.InvariantCulture))
.ToList()
.AsEnumerable() // added to comply to the desired signature
)
.ToList() // added to comply to the desired signature
;
It first selects the string, splits it on spaces, and then parses the strings in the string array to doubles. That output is converted to a list.
You can do something like this:
var texts = new List<string> { "-87.98 65", "-86.98 75", "-97.98 78", "-81.98 65" };
List<List<double>> newList =
texts.Select(t => t.Split(' ').Select(s => Convert.ToDouble(s)).ToList()).ToList();
foreach (var item in newList)
foreach (var item2 in item)
Console.Write(item2 + " ;");
Output : -87,98; 65; -86,98; 75; -97,98; 78; -81,98; 65;
But i wouldn't call it 'a short way'...
This fits the signature:
var texts = new List<string> {"-87.98 65", "-86.98 75", "-97.98 78", "-81.98 65"};
List<IEnumerable<double>> numerics =
texts.Select(s => new List<double>(s.Split().Select(sub => Double.Parse(sub, CultureInfo.InvariantCulture))))
.Cast<IEnumerable<double>>()
.ToList();

Convert a DataTable to multidimensional array C#

I'm trying to convert a DataTable's rows into multidimensional array:
DataTable DT = new DataTable();
DT.Columns.AddRange
(
new DataColumn[]
{
new DataColumn("LA_ID"),
new DataColumn("contractid")
}
);
for(int i=1000; i<=1100; i++)
DT.Rows.Add(i, i);
EnumerableRowCollection<DataRow> appsEnum = DT.AsEnumerable();
int[,] apps = appsEnum.
Where(x => x.Field<int>("LA_ID") > 1050).
Select(x => x.Field<int>("LA_ID"), x.Field<int>("contractid")).
--Error Here-------------------------------------^
ToArray();
Can anyone help plz.
There is no version of .ToArray() that supports more than 1 dimension. You will need a for-loop here.
It could probably work with a int[][] but not for int[,]
the best you can get with ToArray() method is jagged array
int [][] apps = appsEnum.
Where(x => x.Field<int>("laid") > 1050).
Select(x => new int[] {x.Field<int>("LA_ID"), x.Field<int>("contractid")}).
ToArray();
consider another approach
DataRow[] rows = DT.Select("laid > 1050");
int[,] apps = new int[rows.Length, 2];
for(int r=0; r<rows.Length; r++)
{
apps[r,0] = rows[r].Field<int>("LA_ID");
apps[r,1] = rows[r].Field<int>("contractid");
}

Categories

Resources