Repeat a row multiple times in a gridview - c#

I have a Gridview with a column called Quantity. Each product has it own quantity. I need to show as many rows as the quantity says.
For example, if I have
Car | 4 | $ 20
I need to show 4 rows like
Car | 1 | 20
I can't find a way of doing this. I am using linq to retrieve the data from the database and that is the DataSource of my Gridview.

You can do it using the linq Range method. Assuming you have a linq source like this (trivial example)
var result =
from r in db.SourceTable
select new { r.Name, r.Quantity, r.Price };
Add this to the query
var result =
from r in db.SourceTable
from s in Enumerable.Range(1, record.Quantity)
select new { r.Name, 1, r.Price };
However, this is probably not supported by entity framework (and probably not in any other ORM) so you may need to call .ToList() or .AsEnumerable() first.

Related

Compare two DataTables with several keys and select the rows that are not present in second table

I have two DataTables and I want to select the rows from the first one which are not present in second one, both tables have 3 Keys custnum, shiptonum, connum
For example:
Table Contacts
custnum shiptonum connum column
1 1 1 data1
2 2 2 data2
3 3 3 data3
4 4 4 data4
Table Invitations
custnum shiptonum connum column
1 1 1 data11
3 3 3 data33
I'd like the result to be:
Table Result
custnum shiptonum connum column
2 2 2 data2
4 4 4 data4
I already tried using
var differences = table1.AsEnumerable().Except(table2.AsEnumerable(),DataRowComparer.Default);
but it didn't work. For example in my testing in Contacts table I have 14,389 records, in Invitations table I have two records that exist in Contacts table the count after using the abovesolution was 14,389 instead of 14,387 (removing the two records from Invitations table).
You wrote:
I want to select the rows from the first one which are not present in second one
From your example, I see that you don't want to select rows from the first table that are not rows in the second table, but that you only want to take the values of the keys into account:
I want to select all rows from tableA which have keys with values that are not keys from tableB
You didn't define your tables. They might be IQueryable, or IEnumerable, for your LINQ statements there is not a big difference. Try to avoid AsEnumerable, especially if your data source is in a different process, like a database management system. The other process is much more efficient in executing your query than your process. AsEnumerable transports all data from your other process to your process, which is a relatively slow process. Therefore as a rule: Only use AsEnumerable this if you really need to,
The second definition defines clearer what you want: apparently from tableB you only need the keys:
var keysTableB = tableB.Select(row => new
{
CustNum = row.custNum,
ShipToNum = row.shiptonum,
ConNum = row.connum,
});
In words: from every row in tableB make one new object of anonymous type with three properties: CustNum, ShipToNum and ConNum
Select uses lazy execution. No query is executed, only property Expression is changed.
Now you want to keep only the rows from tableA that have a key that is a member of sequence keysTableB: if you want to keep a subset of a sequence, use Where
var result = tableA.Where(row => keysTableB.Contains(new
{
CustNum = row.custNum,
ShipToNum = row.shiptonum,
Connum = row.connum,
}));
In words: from every row in tableB keep only those rows that have a key that is also in keysTableB, using value equality.
TODO: consider concatenating these two LINQ statements into one.I doubt whether this would improve performance. It surely will deteriorate readability of your code, and thus decreases changeability / maintenance / testability.
for (int i=0;i<table1.rows.count;i++)
{
var rowExists = from dr in table2.AsEnumerable()
where dr.Field<typeofcolumn>("colum_name")==table1.Rows[i]["column_name"]
select dr;
if(rowExists.ToList().Count==0)
{
//here u import row table1.rows[i] to new table
}
}

Implementing the All functionality in SQL

I'm trying to write an SQL query where all of a certain group meets a condition.
Update
The Simplifed Table Structure would look like this
ID, TitleID, BlockFromSale
---------------------------
1 | 1 | true
2 | 1 | true
3 | 1 | true
4 | 2 | false
5 | 2 | true
this table would only return the the items TitleID 1.
In actuality I only need the title ID and not the whole item but either will satisfy the conditions.
How Could I write This Linq Query in SQL?
var Query = Data.Items.GroupBy(t => t.TitleID).Where(i => i.All(b => b.BlockFromSale == true));
I try to look at the Sql Query but it just instantly casts it to an object.
Basically I just Need a query that Grabs out all TitleIDs who for each item BlockFromSale is set to true so for the example from the table above it would only return TitleID, 1
It is possible to see the generated SQL of a LINQ query by using the Log property of the query. How to: Display Generated SQL shows an example of this. Basically, the web site shows this example:
db.Log = Console.Out;
IQueryable<Customer> custQuery =
from cust in db.Customers
where cust.City == "London"
select cust;
foreach(Customer custObj in custQuery)
{
Console.WriteLine(custObj.CustomerID);
}
If you want to check predicate p for all rows of a set you can write
NOT EXISTS (... WHERE NOT(p))
Because All(p) == !Any(!p) in pseudo-syntax.
I would guess that ORMs do it this way, too.
There isn't an easy way to do what your asking but a simple but some what slow way would be to use a subQuery
SELECT DISTINCT i.TitleID
FROM Items i
WHERE i.TitleID not in
(SELECT DISTINCT TitleID
FROM items it
WHERE it.BlockFromSale = 0)
so it will remove the titleids who have a false.

Linq List Contains Method

Im newbie to linq and im using linq query to retrieve data from the table.My idea is to list all the cashsafes corresponding to a particular user and show it in dropdownlist.
The table structure is shown below
Table 1
cashsafeid cashsafename
1 cashsafe1
2 cashsafe2
3 cashsafe3
Table 2
Id UserId Cashsafeid
1 100 1,2,3
2 101 1,3
I've to get the cashsafename of a particular user say 100.How can i achieve it
The below code is the one i've tried but am stuck
List<Cashsafe> cashsafes=(from c in db.Table 1
where c.CashsafeId contains() )--Cannot go further
You store User's Cachsafeid column in very inefficient way - it doesn't allow to generate efficient SQL for LINQ provider. So the following solution has bad performance - if you care about that - change your table structure.
var user = db.Table2.Single(u => u.UserId == 100);
var cachfeIds = user.Cashsafeid.Split(',').Select(int.Parse).ToArray();
var cachefes = db.Table1.Where(c => cachfeIds.Contains(c.Id)).ToList();
Basically you need to join to tables, but foreign key is "virtual" - it is only in your mind. To retrieve foreign key values we must split the Cachsafeid column's value of every user to retrieve linked cachefes. And only then retrieve the cachefes with separate request (I think LINQ will retrieve all values from table and the execute Where part in C# code).
if you have no idea of join you can use
int x = 0;
List<int> Users = db.table2.FirstOrDefault(m => m.UserId == 100).Cashsafeid.Split(',').ToList().Where(str => int.TryParse(str, out x)).Select(str => x).ToList(); ;
var content = db.table1.Where(m => Users.Contains(m.cashsafeid)).ToList();

Querying for a specific value at the intersection of a Row and a Column in a DataTable

Lets say I have a DataTable (myDatable) whose first line is a row of headers and whose subsequent rows are simply numerical data. For example:
| WaterPercent | Ethylene | Toluene |
|1.0312345 | 74.1323 | 234.000 |
|56.054657 | 18.6540 | 234.000 |
|37.57000 | 94.6540 | 425.000 |
At this point, all of its data contained within its myDataTable.Columns and myDataTable.Rows are Strings.
using this query:
var results = from row in myDataTable.AsEnumerable()
select row.Field<string>("Ethylene");
I can get all of the values in the Ethylene column, but I want to filter my query with a "where" clause such that I can retrieve just one value at the intersection of a specific row index and a column like "Ethylene".
Consequently it doesn't look like (unless I am missing something) that i can get access to the index of the rows collection using 'row' in a Linq query. Even if I had this, I am not sure how to form the "where" clause of my query to get what I want.
What do I need for my query to be able to filter the result down to the intersection of a specific row and a column?
For example I want the value 18.6540 which exists at the row index of 2 and the column of Ethylene.
If you know the specific row index, then you can specify row index directly using .Rows collection, like you would index an array or collection (since it's 0-based indexing, row 2 would be index 1):
var result = myDataTable.Rows[1].Field<String>("Ethylene")
Is there a reason you do not do it in the result?
var results = (from row in myDataTable.AsEnumerable()
select row.Field<string>("Ethylene")).ToArray();
then just index
var myVal = results[2];
Otherwise, you will want to use Skip() and Take().
String result = (from row in myDataTable.AsEnumerable()
select row.Field<string>("Ethylene")).Skip(2).Take(1).Single();

How do i get the top 5 items in a database based on the occurence of a particluar field?

Using Ado.Net Entity framework, I am trying to get the 'top 3' items in a table based on the amount of times they appear in a table.
For example:
Table:
basket_to_product_id | basket_id | product_id
I want to see how many times product_id occurs, and would like to return the top 3 product_ids that occur the most frequently.
I'm stuck at:
List<BasketToProduct> btplist = entities.BasketToProduct. ..........?
Something like this should work (of course I do not know the actual names of your properties):
IEnumerable<int> top3ProductIds = (from btp in entities.BasketToProduct
group btp by btp.ProductId into g
orderby g.Count() descending
select g.Key).Take(3);
You could try to use a LINQ query on the table.
Try this:
var query = entities.BasketToProduct
.GroupBy(btp => btp.ProductID)
.Select(g => ProductID = g.Key, Count = g.Count())
.OrderBy(g => g.Count)
.Take(3);
It'll get you the top three ProductIDs and their associated counts.

Categories