DataTable's Row's First Column to String Array - c#

I have a DataTable. I want to get every rows first column value and append to a string array. I do not want to use foreach looping for every row and adding to string array. I tried this, but stuck at some point
DataRow[] dr = new DataRow[dtCampaignSubscriberLists.Rows.Count];
dtCampaignSubscriberLists.Rows.CopyTo(dr, 0);
string[] array = Array.ConvertAll(dr, new Converter<DataRow, String>(????));
Thanks

string[] array = yourTable
.AsEnumerable()
.Select(row => row.Field<string>("ColumnName"))
.ToArray();

You could do something like:
dtCampaignSubscriberLists.AsEnumerable().Select(r => r[0].ToString()).ToArray();

Related

How to get columns with values from second list which is contain in first list?

I have two list. First list has matched column which is available in second list.
I want to show matched columns with values from second list.
List<string> _filtredData = new List<string>();
_filtredData.Add("Broker");
_filtredData.Add("Loaction");
_filtredData.Add("StandardLineItem");
_filtredData.Add("Section");
foreach (DataColumn _dtCol in FinalDiffData.Columns)
{
if (matchedItems.Contains(_dtCol.ToString()))
{
_filtredData.Add(_dtCol.ToString());
}
}
_filtredData -> contains matched columns which available in Second list.
FinalDiffData.AsEnumerable() -> this is secondlist.
List<string> _filtredData = new List<string>();
_filtredData.Add("Broker");
_filtredData.Add("Loaction");
_filtredData.Add("StandardLineItem");
_filtredData.Add("Section");
foreach (DataColumn _dtCol in FinalDiffData.Columns)
{
if (matchedItems.Contains(_dtCol.ToString()))
{
_filtredData.Add(_dtCol.ToString());
}
}
var shortedListMismatchElementLocal = _filtredData;
var result = FinalDiffData.AsEnumerable().Where(p =>
shortedListMismatchElementLocal.Any());
Please help me with proper answer.
Edit from your last comment
FinalDiffData.AsEnumerable() list has column like
Broker, Loaction, StandardLineItem, Section, 2Q2019E, 3Q2019E, 4Q2019E, 2019E, 1Q2020E
etc as earning order. _filtredData list has
Broker, Loaction, StandardLineItem, Section, 2Q2019E, 3Q2019E, 4Q2019E,
I want to get matched column with value from FinalDiffData.AsEnumerable() which available in _filtredData list
You need to compare a List<string> with a DataTable. You're only interested in one column in the datatable (I'll assume the column name is "Data").
The following query will get all rows in column "Data" matching _filteredData.
var result = FinalDiffData
.AsEnumerable()
.Where(p => _filtredData.Contains(p["Data"])); // use the actual column name here

Insert datagridview column values into an Array c#

In my form I have this DataGridView (grid1), filled from a sqllite database.
I want select the column with the name "cap" and insert the column's values into an array.
How can I do?
I don't find a way to select the column cap by name, so I decided to indicate it with the index, but I don't like this way..
I don't know ho to insert these values into an array. there are a lot of columns/cell method but I don't figured out which one can help me!
I tryed to do this way (from an old answer here in the site) but it gives me error of "out of bounded matrix"
int[] wareCap = new int[grid1.Rows.Count];
...
//How I filled my dgv, if this can help
var context = new ForliCesenaEntities2();
BindingSource bi1 = new BindingSource();
bi1.DataSource = context.warehouses.ToList();
grid1.DataSource = bi1;
grid1.Refresh();
//How I try to insert the values into int[] wareCap
for (int i = 0; i<(grid1.Rows.Count-1); i++)
wareCap[i] = Convert.ToInt16(grid1.Rows[i].Cells[1].Value);
Thanks in advice
First you gridview has to be filled with values, then:
List<int> intValues = new List<int>();
foreach (DataGridViewRow row in grid.Rows)
{
intValues.Add(int.Parse(row.Cells["cap"].Value.ToString()));
}
int[] array = intValues.ToArray();
should do the trick.
Alternatively, you could use LINQ.
int[] intArray = dataGridView1.Rows
.Cast<DataGridViewRow>()
.Select(row => int.Parse(row.Cells["cap"].Value.ToString())).ToArray();
UPDATE:
The above solution might crash if the DataGridView's AllowUserToAddRows property is set to true. Because in that case your last row is the row for entering a new record, the Value is null, so invoking the ToString method on it causes a NullReferenceException.
I see two possibilities:
set your datagridview's AllowUserToAddRows property to false (but the user won't be able to add new rows),
use the following solution
Check if the row is the row for entering a new record:
int[] intArray = dataGridView1.Rows
.Cast<DataGridViewRow>()
.Where(row => !row.IsNewRow)
.Select(row => Convert.ToInt32(row.Cells["cap"].Value.ToString())).ToArray();
You already got all your values in a List, because you do sth. like this:
bi1.DataSource = context.warehouses.ToList();
You can easily store this in a reference:
var values = context.warehouses.ToList();
bi1.DataSource = values;
Your Grid is build based on Objekts in this List. So this should build your array:
int[] array = new int[values.Count];
int counter = 0;
foreach (var object in values)
{
array[counter++] = object.CAP;
}
int[] wareCap = new int[grid1.Rows.Count];
foreach(DataGridViewRow row in grid1.Rows)
{
wareCap.Add(Convert.ToInt32(cell["cap"].Value.ToString()));
}

Linq: select where in List<string>

Struggeling with some LinqToExcel filtering here...
Ive got a List<string> columnsToFilter that contains 9 strings, and with that i want to filter out the data for certain columns in a List<Row>, where Row contains the properties
IEnumerable<string> ColumnNames
Cell this[string columnName]
So: List<Row> has say 30 rows, each having 12 ColumnNames. Now i want to filter that List<Row> using List<string> columnsToFilter so that i end up with a List<Row> of 30 rows and 9 ColumnNames.
I can select the data for one column by quering the columnname:
var result = content.Select(m => m["Column1"]).ToList();
Now i want to filter the data based on a List of strings List<string> columnsToFilter. Whats the best way to achieve that?
Is this what you are looking for?
var colnames = new List<string>();
var rows = new Dictionary<string, object>();
var result = rows.Where(kv => colnames.Contains(kv.Key)).Select(kv => kv.Value);
Define an object called MyObject which has the property names corresponding to the 9 columns that you want to select.
var excel = new ExcelQueryFactory("excelFileName");
var myObjects = from c in excel.Worksheet<MyObject>()
select c;
Bingo. You can now iterate through the 30 objects with the 9 columns as properties.
Remember that LinqToExcel will happily fill objects even if they don't have all the columns represented.
You could even have a property or method as part of MyObject called "row" that would be a Dictionary() object so you could say myObject.row["ColumnName"] to reference a value if you preferred that syntax to just saying myObject.ColumnName to get the value. Personally I would rather deal with actual properties than to use the dictionary convolution.
I ended up doing this in two steps:
foreach (var column in columnNumbers)
{
yield return data.Select(m => m[column].Value.ToString()).ToList();
}
Now I have the data I need, but with the rows and columns swapped, so i had to swap rows for columns and vice versa:
for (int i = 1; i < rowCount; i++)
{
var newRow = new List<string>();
foreach (var cell in list)
{
newRow.Add(cell[i]);
}
yield return newRow;
}

Linq to sql between List and Comma separated string

I Have one list and one comma separated column value.
lst.Add("Beauty");
lst.Add("Services");
lst.Add("Others");
And Column value is like
Beauty,Services
Service,Others
Beauty,Others
Other,Services
Other
Beauty, Food
Food
Now I Want all those rows which contains any list item.
Output result is
Beauty,Services
Service,Others
Beauty,Others
Other,Services
Other
Beauty, Food
First Edit
These comma separated values are one of my table's one column value.
I need to check against that column.
Assuming you can figure out how to get the RowCollection
RowCollection.Where(row => row.Split(",").ToList().Where(x => list.Contains(x)).Any()).ToList();
will evaluate to true if the row contains a value from the list.
try
List<string> lst = ....; // your list of strings
string[] somecolumnvalues = new string[] { "", "",... }; // your columvalues
var Result = from l in lst from c in somecolumnsvalues where c.Contains (l) select c;

How to get a particular row from a DataRow[]?

DataRow[] headerRows = null;
headerRows = mappingTable.Select("FieldID LIKE '0_%'"); //mappingTable is of type DataTable.
I have three columns in the mappingTable "Id","Display", "Value"
Now, I need to get the Value where "Id" = 0_0_0 from the headerRows.
Is there any simple way to do this?
Thanks for any help.
If you have to use DataRow[] then with linq you can do this:
String value = (String)rows.Single(
row => String.Equals(row["Id"], "0_0_0"))["Value"];
You need to set the PrimaryKey on the DataTable and then you can use Find() on the Rows collection to find the row with that key.
dataTable.PrimaryKey = new DataColumn[] { dataTable.Columns["Id"] };
object value = dataTable.Rows.Find("0_0_0")["Value"];
You could use LINQ: but this might be overkill:
dt.AsEnumerable().Where(dr => dr.Field<object>("FieldId").StartsWith("0_"));
If you have to have DataRow[] then
headerRows = dt.AsEnumerable().Where(dr => dr.Field<object>("FieldId").StartsWith("0_")).ToArray();
From there you have only data rows that match your criteria, so you can cycle through for the value.

Categories

Resources