Choose second var array in a list - c#

How do I choose the second var array in the list? array[i+1] chooses the second column but I want to begin with the second row of the array. So I would like to disregard the first row, since this contains the column names.
Code:
foreach(var array in list)
{
var NewRow = table.NewRow();
for (int i = 0; i < columnNames.Count; i++)
{
NewRow[columnNames[i]] = array[i];
}
table.Rows.Add(NewRow);
}
EDIT: Whole method
private DataTable ConvertListToDataTable(List<WindowsFormsApplication1.ServiceReference1.ArrayOfString> list)
{
DataTable table = new DataTable();
List<string> columnNames = list[0];
for (int i = 0; i < columnNames.Count; i++)
{
table.Columns.Add(columnNames[i].ToString());
}
foreach (var array in list)
{
var NewRow = table.NewRow();
for (int i = 0; i < columnNames.Count; i++)
{
NewRow[columnNames[i]] = array[i];
}
table.Rows.Add(NewRow);
}
return table;
}

You could use Skip
foreach (var array in list.Skip(1))
{
...
}
Or alternatively, stick with a basic for loop and just start at 1
for (var i = 1; i < list.Count; i++)
{
...
}

You can use Skip:
foreach (var array in list.Skip(1))
{
var NewRow = table.NewRow();
for (int i = 0; i < columnNames.Count; i++)
{
NewRow[columnNames[i]] = array[i];
}
table.Rows.Add(NewRow);
}
Don't forget to add using System.Linq; at the top of the file.

Related

I want to read a table from text file and assign each column to an array

i want to store each row in a different array. below is the code i tried.
but it doesn't not work, it only splits the last line and store values in "valueperline" array
first 11 rows are source text. file and screen shot of console
using System;
using System.Collections.Generic;
using System.IO;
namespace BBS_optimize
{
class Program
{
static void Main()
{
int i = 0; int j = 0; int k =0; string[] valueperline = new string[0]; string[] lines = new string [0];
lines = File.ReadAllLines("Table1.txt");
for (i = 0; i < lines.Length; i++)
{
Console.WriteLine(lines[i]);
}
for (j = 0; j<lines.Length; j++)
{ valueperline = lines[j].Split('\t');
}
for (k = 0; k < 44; k++)
{ Console.WriteLine(valueperline[k]);
}
}
}
}
Use array:
string[,] ParseFromFile (string fileName)
{
// Assume that your table have 10 cols and 100 rows
string[,] result = new string[10,100];
string str = File.ReadAllText (fileName);
// Split each line to arrays
string[] yourStringArray = str.Split(new[]{'\r', '\n'},StringSplitOptions.RemoveEmptyEntries);
for (int i == 0; i < yourStringArray; i++)
{
string[] row = yourStringArray[i].Split(new[]{" "},StringSplitOptions.RemoveEmptyEntries);
result[i] = row;
}
return result;
}
Use List:
List<List<string>> ParseFromFile (string fileName)
{
// Your list
List<List<string>> result = new List<List<string>>();
string str = File.ReadAllText (fileName);
// Split each line to arrays
string[] yourStringArray = str.Split(new[]{'\r', '\n'},StringSplitOptions.RemoveEmptyEntries);
for (int i == 0; i < yourStringArray; i++)
{
List<string> row = yourStringArray[i].Split(new[]{" "},StringSplitOptions.RemoveEmptyEntries).ToList();
result.Add(row);
}
return result;
}
below is a solution:
static void Main(string[] args)
{
List<List<string>> lst = new List<List<string>>();
string[] lines = new string[0];
lines = File.ReadAllLines("tableX.txt");
for (int i = 0; i < lines.Length; i++)
{
Console.WriteLine(lines[i]);
}
for (int j = 0; j < lines.Length; j++)
{
var line = lines[j].Split(' ').ToList();
lst.Add(line);
}
foreach (var item in lst)
{
for (int k = 0; k < item.Count; k++)
{
Console.WriteLine(item[k]);
}
}
}

List<T> to datatable returns empty - WPF

I am using below code to populate datatable from List<double[]> list
But the datatable is not populated.
private void LoadThis(object sender, EventArgs e)
{
X model = DataContext as X;
List<double[]> list = new List<double[]>();
for (int i = 0; i < model.RowFijtable; i++)
{
double[] rowdata = new double[model.ColFijtable];
for (int j = 0; j < model.ColFijtable; j++)
{
rowdata[j] = model.TauTable[i, j];
}
list.Add(rowdata);
}
DataTable table = ConvertListToDataTable(list);
dataGridView1.ItemsSource = table.AsDataView(); //Is this correct?
}
private DataTable ConvertListToDataTable(List<double[]> list)
{
DataTable table = new DataTable();
// Get max columns.
int columns = 0;
foreach (var array in list)
{
if (array.Length > columns)
{
columns = array.Length;
}
}
// Add columns.
for (int i = 0; i < columns; i++)
{
table.Columns.Add();
}
// Add rows.
foreach (var array in list)
{
table.Rows.Add(array);
}
return table;
}
This is how I placed the information in XAML
<Grid>
<DataGrid HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Name="dataGridView1"
Loaded="LoadThis"
ItemsSource="{Binding}"
AutoGenerateColumns="True"/>
</Grid>
I can see that the number of columns and rows are passed on correctly to the datatable but no data values even though List has complete dataset!
I also tried doing dataGridView1.DataSource = table; but this keeps me error as "Datagrid does not contain the definition of DataSource"..
Calling table.Rows.Add(array) seems to put the entire array into the first column value. To put the array elements into successive columns, try this:
private DataTable ConvertListToDataTable(List<double[]> list)
{
DataTable table = new DataTable();
// Get max columns.
int columns = 0;
foreach (var array in list)
{
if (array.Length > columns)
{
columns = array.Length;
}
}
// Add columns.
for (int i = 0; i < columns; i++)
{
// Provide default column name & data type
table.Columns.Add("Column" + (i+1).ToString(), typeof(double) );
}
// Add rows.
foreach (var array in list)
{
// assign each array element to the appropriate column
var row = table.NewRow();
for (int i = 0; i < array.Length; ++i )
row.SetField( i, array[i] );
table.Rows.Add(row);
}
return table;
}

not to read empty or null records in datatble from text file - c#

I have a function which reads all the tab delimited records from a text file into a datatble, but I have a lot empty or null columns also which are tab delimited. I just want to read all records where column 3 is not null or non empty. how can I do it?
Here is my simple method
public DataTable ConvertTextToDataTable(string filePath, int numberOfColumns)
{
DataTable tbl = new DataTable();
for (int col = 0; col < numberOfColumns; col++)
tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));
string[] lines = System.IO.File.ReadAllLines(filePath);
int i = 0;
foreach (string line in lines)
{
var cols = line.Split('\t');
DataRow dr = tbl.NewRow();
for (int cIndex = 0; cIndex < numberOfColumns; cIndex++)
{
dr[cIndex] = cols[cIndex];
}
tbl.Rows.Add(dr);
i++;
}
return tbl;
}
The simplest would be to insert a check for IsNullOrWhiteSpace for column 3 before creating and and adding values to the datatable like:
public DataTable ConvertTextToDataTable(string filePath, int numberOfColumns)
{
DataTable tbl = new DataTable();
for (int col = 0; col < numberOfColumns; col++)
tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));
var lines = System.IO.File.ReadLines(filePath);
int i = 0;
foreach (string line in lines)
{
var cols = line.Split('\t');
if (cols.Length > 3 && String.IsNullOrWhiteSpace(cols[3]))
{
continue; //Ignore this line
}
DataRow dr = tbl.NewRow();
for (int cIndex = 0; cIndex < numberOfColumns; cIndex++)
{
dr[cIndex] = cols[cIndex];
}
tbl.Rows.Add(dr);
i++;
}
return tbl;
}
Also notice the use of var lines = System.IO.File.ReadLines(filePath); instead of File.ReadAllLines, since it will evaluate the file line by line, instead of loading up all the files content in memory.

How to iterate over a multidimensional string array?

I have a 2d string array (at least I think it is called a 2d array):
var target = new string[var1,var2];
Now I want to convert it to List<List<string>>:
var listlist = new List<List<string>>();
foreach (var row in target)
{
var newlist = new List<string>();
foreach (var el in row)
{
newlist.Add(el);
}
listlist.Add(newlist);
}
But row has a type is string and el has type is char.
I can't understand why el is not a string? What's wrong?
A foreach interates over a string[,] like it is a string[]. It doesn't split in rows.
If you do want to handle 'rows' and 'columns' those separately, you have to get the dimensions of the array, using the GetLength method:
var target = new string[var1, var2];
var listlist = new List<List<string>>();
for (int x = 0; x < target.GetLength(0); x++)
{
var newlist = new List<string>();
for (int y = 0; y < target.GetLength(1); y++)
{
newlist.Add(target[x, y]);
}
listlist.Add(newlist);
}
This is what you need
static void SoStrList()
{
int var1=10, var2=7;
var target=new string[var1, var2];
var listlist=new List<List<string>>();
for(int i=0; i<var1; i++)
{
var row=new List<string>();
for(int j=0; j<var2; j++)
{
row.Add(target[i, j]);
}
listlist.Add(row);
}
}
use for loop instead of foreach
var target = new string[2, 2];
target[0, 0] = "a";
target[0, 1] = "A";
target[1, 0] = "b";
target[1, 1] = "B";
var listlist = new List<List<string>>();
for (int i = 0; i < target.GetLength(0); i++)
{
var newlist = new List<string>();
for (int j = 0; j < target.GetLength(1); j++)
newlist.Add(target[i,j]);
listlist.Add(newlist);
}
Here:
foreach (var row in target)
You already have first element of your 2d array, and foreach take all chars of this elements
well ... string is array of chars.
And this confusion is what you get from using keyword var for almost everything. Its not javascript.
Secondly : You need to go for something like this
for (int i = 0; i < target.GetLength(0); i++)
{
for (int y = 0; y < target.GetLength(1); y++)
{
your manipulation with strings
}
}
but srsly... get rid of vars !!!
For LINQ lovers, the same can be achieved using the following two lines:
int R = s.GetLength(0), C = s.GetLength(1);
var MyList = Enumerable.Range(0, R).Select(i => i * C).Select(i => s.Cast<string>.Skip(i).Take(C).ToList()).ToList();

Reading data from DataGridView in C#

How can I read data from DataGridView in C#? I want to read the data appear in Table. How do I navigate through lines?
something like
for (int rows = 0; rows < dataGrid.Rows.Count; rows++)
{
for (int col= 0; col < dataGrid.Rows[rows].Cells.Count; col++)
{
string value = dataGrid.Rows[rows].Cells[col].Value.ToString();
}
}
example without using index
foreach (DataGridViewRow row in dataGrid.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
string value = cell.Value.ToString();
}
}
If you wish, you can also use the column names instead of column numbers.
For example, if you want to read data from DataGridView on the 4. row and the "Name" column.
It provides me a better understanding for which variable I am dealing with.
dataGridView.Rows[4].Cells["Name"].Value.ToString();
Hope it helps.
string[,] myGridData = new string[dataGridView1.Rows.Count,3];
int i = 0;
foreach(DataRow row in dataGridView1.Rows)
{
myGridData[i][0] = row.Cells[0].Value.ToString();
myGridData[i][1] = row.Cells[1].Value.ToString();
myGridData[i][2] = row.Cells[2].Value.ToString();
i++;
}
Hope this helps....
Code Example : Reading data from DataGridView and storing it in an array
int[,] n = new int[3, 19];
for (int i = 0; i < (StartDataView.Rows.Count - 1); i++)
{
for (int j = 0; j < StartDataView.Columns.Count; j++)
{
if(this.StartDataView.Rows[i].Cells[j].Value.ToString() != string.Empty)
{
try
{
n[i, j] = int.Parse(this.StartDataView.Rows[i].Cells[j].Value.ToString());
}
catch (Exception Ee)
{ //get exception of "null"
MessageBox.Show(Ee.ToString());
}
}
}
}
private void HighLightGridRows()
{
Debugger.Launch();
for (int i = 0; i < dtgvAppSettings.Rows.Count; i++)
{
String key = dtgvAppSettings.Rows[i].Cells["Key"].Value.ToString();
if (key.ToLower().Contains("applicationpath") == true)
{
dtgvAppSettings.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
}
}
}

Categories

Resources