I am bit new to linq .
How do I get the total sum of two columns in my data table.
Let say 2 columns are A& B . I want numeric sum of entire column A and entire column B
(i.e totalSum= sum(A)+sum(B))
IMP :
If I have any field in either of 2 columns a non numeric field (eg AB,WH,DBNULL) . That field should be considered as zero while summing up the values so that it wont throw any exception.
For each row or the sum of entire column A and entire column B?
In the first case you could do a select:
var resultWithSum = from row in table
select new{
A = row.A, //optional
B = row.B, //optional
sum = row.A + row.B
}
Otherwise you can do:
result = table.Sum(row => row.A + row.B)
Related
In my database, each letter has its own column, but when I add words to the column, it goes to the bottom and Null fields are created
Now so
And I need it this
I have a list of words and the word must fall into the column from which the first letter of the word begins
My Code
private void ConnectData()
{
_path = "URI=file:" + Application.streamingAssetsPath + "/russianWords.db"; //Path to datab
_dbConnection = new SqliteConnection(_path);
_dbConnection.Open();
if (_dbConnection.State == ConnectionState.Open)
{
m_sqlCmd = new SqliteCommand();
m_sqlCmd.Connection = _dbConnection;
m_sqlCmd.CommandText = "CREATE TABLE IF NOT EXISTS words (а Text , б Text ,в Text,г Text,д Text,е Text,ё Text,ж Text,з Text,и Text,й Text,к Text,л Text,м Text,н Text,о Text,п Text,р Text,с Text,т Text,у Text,ф Text,х Text,ц Text,ч Text,ш Text,щ Text,ъ Text,ы Text,ь Text,э Text,ю Text,я Text)";
m_sqlCmd.ExecuteNonQuery();
}
AddToData("sddd", "т");
}
public void AddToData(string word)
{
try
{
m_sqlCmd.CommandText = $#"INSERT INTO words ('{word.ToCharArray()[0].ToString()}') values ('{ word }')";
m_sqlCmd.ExecuteNonQuery();
}
catch (System.Exception e)
{
Debug.Log(e);
}
}
Databases don't work like this. Putting data in a table will always make a new row. It is not like a game of upwards- Tetris where you insert "Fred" into column "F" and it will find the first empty slot (nearest the "top") and put it there. There isn't even the sense of "top" - datatable tables are just a bunch of rows stored in whatever order the database feels like. If you want your data to have an order you must insert some data that has an order (like an int) and sort by it
If you want this "Tetris" style behavior you must program it explicitly. Have a column that is incrementing numbers
ID A B C
1
2
You want to insert Apple. Select the lowest ID where the column is blank
SELECT MIN(id) FROM t WHERE A IS NULL
ExecuteScalar that and cast the result to an int?
If there is an ID, update it. Otherwise insert:
UPDATE t SET A = 'Apple' WHERE ID = 1
ID A B C
1 Apple
2
Now we want to insert Aeroplane. It will go in ID 2 by the same logic
ID A B C
1 Apple
2 Aeroplane
Now we insert Aurora. There is no row 3. The SELECT that finds the ID will return no rows (you'll get a null returned from execute scalar)
Run the following insert
INSERT INTO t(ID, A)
SELECT MAX(id)+1, 'Aurora' FROM t
ID A B C
1 Apple
2 Aeroplane
3 Aurora
You now have aurora in ID 3
Continue thus either inserting or updating. You should thus have at least one column that is completely full all the time and the others will fill in as they go..
--
Consider to use any auto numbering facility your chosen db has rather than max+1 (but max+1 would work)
I can't figure out how to solve this. I want to calculate in datagridview
Column 3 like this
using C#
Check this
int sum = 0;
for(int i=0;i<dataGridView1.Rows.Count;i++)
{
sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value);
}
MessageBox.Show(sum.ToString());
To calculate values from you datagridview, you can do several approaches
For example, you can retrieve by rows then reference the column of the cell by index or column name.
For example, adding values in "Column 3" would be:
var rows = dataGridView1.rows;
double sum = 0;
foreach (DataGridViewRow row in rows)
{
sum += (double)row.Cells["Column 3"].Value;
}
EDIT:
If you're using DataTable (which I presume from your comments) to get individual cell data, you can either reference the row first then adding an index based on the column, or you can create a temp row, then get the value using the column. The records or values within a DataTable are basically just collection of rows.
Example:
int col3 = workTable.Columns.IndexOf("Column 3") -1;
double amount = Convert.ToDouble(workTable.Rows[1][col3]); // 1st value in column 3
OR (extended for clarity)
DataRow row1 = workTable.Rows[1];
double amount = Convert.ToDouble(row1[col3]);
If you need to transpose values into a DataGridView, you can just set the DataSource property of a DataGridView instance i.e.
dataGridView1.DataSource = newFilledTable;
Question title could be confusing because i didn't find appropriate sentence to specify my problem. I have an entity which contains 60 properties [Columns]. Now i want to insert into this entity. Normal insert code would be:
tblEmployee objEmployee= new tblEmployee();
tblEmplyee.Name="abc"; // Col 1
tblEmplyee.Email="abc#abc.com"; // Col 2
tblEmplyee.S1="s1"; // Col 3
tblEmplyee.S2="s2"; // Col 4
.
.
.
tblEmplyee.S60="s60"; // Col 60
db.AddTotblEmployee(objEmployee);
db.SaveChanges();
But i have a condition, i need to insert values in S1 to S60 variably.
e.g case 1: from S1 to S17 value 1, S18 to S50 value 2 and S51 to S60 value 3.
case 2: from S1 to S11 value 1, S11 to S40 value 2, S40 to S43 value 3 and S44 to S60 value 4.
And this pattern can be different every time and depend on user input by UI.
Is there any way to access tblEmployee's column like array indexes ?
tblEmployee objEmployee= new tblEmployee();
tblEmplyee.col["1"]="abc"; // Col 1
tblEmplyee.col["2"]="abc#abc.com"; // Col 2
tblEmplyee.col["3"]="s1"; // Col 3
.
.
.
or any other way?
Hi here is the code you can use
System.Reflection.PropertyInfo[] properties = typeof(tblEmployee).GetProperties();
tblEmployee objEmployee = new tblEmployee();
for(int i=0;i<properties.Length;i++)
{
properties[i].SetValue(objEmployee, 1);//First param is obj and 2nd is value for the column which will be saved in db.
}
The query below will get data from a column to see if the data contains a certain string.
This is string is found in that column I would like to select all of the data within them rows. For example in the the datatable the will be a row with age[10-20] and based on this input string it should output all of the row the string is age
The code does not return any data, nor are there any errors. Is it possible to select a column based on the index ?
var result = excelDataTable.AsEnumerable().Where(data => data.Field<String>(0).StartsWith(queryString));
Data input 1
Age
Data in DataTable
Age[0-8] 1 1 1
Age[9-11] 2 2 2
season[winter] 4 4 4
Based on the input I want to return
Age[0-8] 1 1 1
Age[9-11] 2 2 2
The Field extension method works also with the index of the column:
var result = importedExcelData.AsEnumerable()
.Where(r=> r.Field<String>(0).Contains(first));
You can select the column name with Select method.
var result = importedExcelData.AsEnumerable()
.Where(data => data.Field<String>("All Respondents")
.Contains(first))
.Select(c=>c.Field<String>(0)).ToList();
I have a DataSet similar to the one below:
ID Name Data1 Data2
1 MM X 1000
2 ST Y 1000
3 EC Z 1000
4 JT T 1000
I display this DataSet in a DataGridView by binding the DataSet. What I would like to do is set the visibility of the Data2 column based on if all the data is similar or not.
So in the above example, I would want to hide the Data2 column because the data represented is common to all elements in the DataSet. But if any of the elements had a unique entry for that column, I would want the column to be visible.
Is there a way to do this without iterating over the DataSet? I prefer not to iterate as my DataSets are quite large and I want to perform this check for multiple columns.
You can use some LINQ to check to see how many distinct values you have in that column:
if(dataTable.AsEnumerable().Select(row => row["Data2"]).Distinct().Count() > 1)
{
// Make column invisible
}
If there is more than 1 distinct value, then you know that not all of the values are equal.
var areSame = dt.Rows.Count > 0 &&
dt.AsEnumerable().All(x => dt.rows[0]["Data2"].Equlas(x["Data2"]));