I have two DataTables:
DataTable dtCatalogFromMySql;
DataTable dtDataForExistingProducts;
dtCatalogFromMySql
Id | productname | barcode | pricesell| type
---+--------------+----------+----------+------
1 | Abz | 123 | 2.01 | RS // different product name
2 | Abd | 122 | 8.90 | RS // different price
3 | Abx | 125 | 21.00 | WS // both different
4 | Abf | 124 | 2.11 | RS
5 | Abg | 126 | 8.01 | WS
6 | Abh | 127 | 60.23 | RS
7 | Abi | 128 | 9.10 | RS
dtDataForExistingProducts
Id | productname | barcode | pricesell| type
---+--------------+----------+----------+------
1 | Abc | 123 | 2.01 | RS
2 | Abd | 122 | 3.90 | RS
3 | Abe | 125 | 23.00 | WS
4 | Abf | 124 | 2.11 | RS
5 | Abg | 126 | 8.01 | WS
6 | Abh | 127 | 60.23 | RS
7 | Abi | 128 | 9.10 | RS
I need return only rows which are different as in first table
I need select all data where Prod_No equals to baracode and Descript not equals to productname and Retail_PRC also not equals to pricesell.
I am not getting results with this code
List<DataRow> matchingRows = dtCatalogFromMySql.AsEnumerable()
.Where(a => dtDataForExistingProducts.AsEnumerable()
.Select(b => b.Field<string>("Prod_No"))
.Contains(a.Field<string>("barcode")))
.Where(a => !dtDataForExistingProducts.AsEnumerable()
.Select(b => b.Field<string>("Descript"))
.Equals(a.Field<string>("productname")))
.Where(a => !dtDataForExistingProducts.AsEnumerable()
.Select(b => b.Field<decimal>("Retail_PRC"))
.Equals(Convert.ToDecimal(a.Field<double>("pricesell"))))
.ToList();
I suppose, Contains() will also fetch the data if barcode = 123456 and Prod_No = 1234, it is right? If I am right what is right way to compare string exactly same
You may want to consider a clearer syntax such as:
var results = from t1 in dtCatalogFromMySql.AsEnumerable()
join t2 in dtDataForExistingProducts.AsEnumerable() on
(string)t1["barcode"] equals (string)t2["Prod_No"]
where (string)t1["productname"] != (string)t2["descript"] &&
Convert.ToDecimal((double)t1["pricesell"]) !=
(decimal)t2["Retail_PRC"]
select t2;
The Join is definitely the way to go. You can modify the select according to your required result set.
trighati makes a good point about using OR instead of AND. This is assuming that you want all of the data where at least one of your values changed where Prod_no and barcode are equal. This would change the query to be:
var results = from t1 in dtCatalogFromMySql.AsEnumerable()
join t2 in dtDataForExistingProducts.AsEnumerable() on
(string)t1["barcode"] equals (string)t2["Prod_No"]
where (string)t1["productname"] != (string)t2["descript"] ||
Convert.ToDecimal((double)t1["pricesell"]) !=
(decimal)t2["Retail_PRC"]
select t2;
Use Join to combine them into one result set, then filter the result set:
var combined = dtDataForExistingProducts.AsEnumerable()
.Join(dtCatalogFromMySql.AsEnumerable(),
ep => ep.Field<string>("Prod_No")
ce => ce.Field<string>("barcode"),
(ep, ce) => new {ExistingProduct = ep, CatalogEntry = ce})
.Where(m => !m.ExistingProduct.Field("Descript")
.Equals(m.CatalogEntry.Field("productname")))
.Where(m => decimal.Parse(m.ExistingProduct.Field("Retail_PRC").ToString())
!= decimal.Parse(m.CatalogEntry.Field("pricesell").ToString()))
.ToList()
;
Related
I have this Linq to Entities (EF Core) query which looks like below
var query = (from p in db.Samples
join q in db.Items on p.Id equals q.SampleId
Where p.active = IsActive and p.Id = GivenId
group new
{
p.Name,
p.Address,
p.Marks,
p.LocationId,
q.EmailId,
q.Grade
}
by new
{ q.Grade }
into data
select new DataSummary()
{
UserName = data.Name,
Grade = data.Min(x => x.Grade),
Email = data.Min(x => x.Email,
Total = data.Sum(x => x.Marks)
}.ToList()
Now I have a constant List of Hashset of Grades and Location that looks like this:
public List<(HashSet<string> Grades, HashSet<Location> Loctions)> LocationGrades => new()
{
(new() { "A", "B" }, new()), // Includes all location
(new() { "C"}, new(){
Location.Boston, //Location is Enum
Location.Maine
}
}
I want to get the data where if the student has grade A or B include all location and if the student has grade C only include Boston and Maine.
Is it possible to integrate this within the LINQ to Entities query?
Sample Table
| ID | Name | Address | Marks | LocationId |
|-----|-------|---------|-------|-------------|
| 234 | Test | 123 St | 240 | 3 (Maine) |
| 122 | Test1 | 234 St | 300 | 5 (Texas) |
| 142 | Test1 | 234 St | 390 | 1 (Boston) |
Items Table
| ID | SampelId | Grade | Email |
|----|----------|-------|-------|
| 12 | 234 | A | a.com |
| 13 | 122 | C | b.com |
| 14 | 142 | C | c.com |
So, In the table above I shouldn't get Texas row but get Boston row as they both have Grade C but Texas does not exist in the HashSet combo.
Okay, now I got it. You have to add dynamic ORed constraints to the query based on a given list of elements. This is a little tricky, because AND can be done with using multiple .Where() statements, but OR not. I did something similar recently against CosmosDB by using LinqKit and the same should also work against EF.
In your case you probably of to do something like this:
...
into data
.WhereAny(grades, (item, grade) => item.Grade == grade)
select new DataSummary()
...
I think the given example doesn't match your exact case, but it allows you to define multiple ORed constraints from a given list and I think this is the missing part you're searching. Take care to use within the lambda method only definitions which are also supported by EF core. The given inner enumeration (in this example grades) will be iterated on the client side and can be dynamically build with everything available in C#.
I have an ObservableCollection<myListType> Items.
Each item in Items has a Project Name which can be "Administrative" and "Non-Administrative"(can be anything). I want to sort my Items using LINQ so that the items with Non-Administrative Project Name will be put on top of Administrative item.
So far i use,
Items.OrderBy(x => x.ProjectName != "Administrative").ThenBy(x => x.ProjectName == "Administrative");
But it doesn't sort the way i want and when i debug, I saw
"The Expression not supported".
Any ideas?
How you use OrderBy and ThenBy shows a lock of understanding how OrderBy works. Please see the following example
| ID | Project Name |
-----------------------
| 1 | Administrative |
| 2 | X |
| 3 | Administrative |
| 4 | X |
With the expression x.ProjectName != "Administrative", OrderBy will look at all items and sort them by whether ProjectName is not "Administrative".
| ID | Project Name | ProjectName != "Administrative" |
---------------------------------------------------------
| 1 | Administrative | false |
| 2 | X | true |
| 3 | Administrative | false |
| 4 | X | true |
This will yield the following order
| ID | Project Name | ProjectName != "Administrative" |
---------------------------------------------------------
| 1 | Administrative | false |
| 3 | Administrative | false |
| 2 | X | true |
| 4 | X | true |
because true is deemed greater by OrderBy. ThenBy now tries to order the groups internally, i.e. all items that matched a single "order key" are tried to be ordered by another criteria. See the following table for visualization
| ID | Project Name | ProjectName != "Administrative" |
---------------------------------------------------------
| 1 | Administrative | false | Items for false
| 3 | Administrative | false |
=========================================================
| 2 | X | true | Items for true
| 4 | X | true |
Since ProjectName == "Administrative" has the same value for all items withing a single group, no subsequent ordering happens.
How can you achieved the desired outcome?
Simply use
Items.OrderBy(x => x.ProjectName == "Administrative")
Since ProjectName == "Administrative" is true for all administrative projects and true is deemed greater by OrderBy they show up last.
According to your requirements, "Non-Administrative" should be put on top of "Administrative".
You can do this:
var list = Items.OrderByDescending(x => x.ProjectName);
it will put "Non-Administrative" before "Administrative".
Edited
[for non-administrative name that has 'AAA']:
var result = Items.OrderBy(p => p.ProjectName == "Administrative").ThenBy(p => p.ProjectName);
Demo on dotnet fiddle
You make sure ProjectName == "Administrative" is always on the bottom.
var result = Items.OrderBy(p => p.ProjectName == "Administrative");
I have datatable looks like this:
| date | value |
| 1/1/2013 10:28 | 5 |
| 1/1/2013 10:29 | 6 |
| 2/1/2013 01:54 | 6.5 |
| 2/1/2013 02:24 | 6.7 |
| 2/1/2013 03:14 | 8 |
I want to group the table into days.
then to calculate the avarage value of every group.
then to make avarage of all the values I calculated in step 2.
is there any good way to do it through linq ?
Thanks
of course you can use linq for this purpose:
var results = from p in list
group p by p.date.Date into g
select new { date = g.Key, value = g.Average(p=> p.value) };
var endAverage = results.Average(x => x.value);
I have an Orders table and an Assignments table which I join together using LINQ to Entities. Each order has a product and a quantity. Each order has a number of assignments up to the quantity. I want to output the following:
Orders:
ID | OrderCode | Quantity | Other Columns...
1 | 30000-1 | 3 | ...
2 | 41000-7 | 2 | ...
Assignments:
OrderID | Assignment | Other Columns...
1 | 4526 | ...
2 | 2661 | ...
2 | 5412 | ...
I want to output a table like:
OrderCode | Assignment
30000-1 | 4526
30000-1 |
30000-1 |
41000-7 | 2661
41000-7 | 5412
Any advice would be welcome!
I would split the task up into three parts.
First, I'd use LINQ to Entities to get the full collection of orders, each with it's corresponding collection of assignments:
var a = (from o in orders
join a in assignments on s.Id equals a.OrderId into oa
//Notice that I use oa.DefaultIfEmpty(). This essentially the way to do a
//LEFT JOIN in LINQ. You'll want to do a LEFT JOIN if you don't
//want to exclude order codes that have no assignments
select new { o.OrderCode, o.Quantity, Assignments = oa.DefaultIfEmpty() })
.ToList();
a returns the following for your example:
OrderCode | Assignment
30000-1 | 4526
41000-7 | 2661
41000-7 | 5412
Then I'd add the "missing" rows
var b = a.SelectMany(o =>
{
var numOrdersInList = o.Count(o2 => o2.OrderCode == o.OrderCode);
return Enumerable.Range(0, o.Quantity - numOrdersInList)
.Select(i => new
{
o.OrderCode,
Assignment = Enumerable.Empty<Assignment>()
});
});
b returns the following for your example:
OrderCode | Assignment
30000-1 |
30000-1 |
Then I'd concat the two enumerables.
var c = a.Select(o => new { o.OrderCode, o.Assignment })
.Concat(b);
Finally, the concatenation should return what you expect for your example:
OrderCode | Assignment
30000-1 | 4526
30000-1 |
30000-1 |
41000-7 | 2661
41000-7 | 5412
First Table
+--------+------------+-------+
| type | variety | price |
+--------+------------+-------+
| apple | gala | 2.79 |
| apple | fuji | 0.24 |
| apple | limbertwig | 2.87 |
| orange | valencia | 3.59 |
| orange | navel | 9.36 |
| pear | bradford | 6.05 |
| pear | bartlett | 2.14 |
| cherry | bing | 2.55 |
| cherry | chelan | 6.33 |
+--------+------------+-------+
Second Table
+--------+----------+
| type | minprice |
+--------+----------+
| apple | 0.24 |
| cherry | 2.55 |
| orange | 3.59 |
| pear | 2.14 |
+--------+----------+
select type, min(price) as minprice
from fruits
group by type;
The first table is and example of the data that I have and the second table is what I want to get from the first.
I am using GenericRepository/UnitOfwork to get the data from repository.
repository.fruitRepository.Get().GroupBy(m => m.type);
But I can only get the type field but I want to get more fields.
Do I need to use a select clause before groupby? If yes, how can I select more fields?
The GroupBy method returns more data, but it's returned as an enumerable... you may be able to pull what you want out of it with a Select after the GroupBy...
repository.fruitRepository.Get()
.GroupBy(m => m.type)
.Select(m => new { type = m.Key, minPrice = m.Min(f => f.Price) });
Or if you prefer a LINQ statement:
var result = from x in repository.fruitRepository.Get()
group x by x.type into typeGroup
select new
{
type = typeGroup.Key,
minPrice = typeGroup.Min(item => item.Price)
};