I have an array of objects with the property of ProductId. I would like to use a lambda expression to select all the distinct values of ProductId that are within my object array products.
Here I get the products
var products = Database.SqlQuery<StructuredProduct>("query").ToArray();
And I can group by distinct values of ProductId, but it still returns an array of objects, rather than an array of ProductIds
var productIds= products.GroupBy(p => p.ProductId).Select(group => group.First()).ToArray();
Any idea on how to use a Lambda Expression on the products array to get all distinct values of ProductIds?
var productIds= products.Select(p => p.ProductId).Distict();
But it may be even better to do this directly on the database, as part of the "query" sql command.
With LINQ method .Distinct()
var productIds = products.Select(p => p.ProductId).Distinct();
I've only ever done GroupBy operations with the query comprehension syntax. If you do that, group / by / into, the thing you group into has a property named key. That would contain your 'productid`
var results = from product in products
group product by ProductId
into individualProducts
select individualProducts;
var productsArray = individualProducts.Select(p => p.Key).ToArray();
The items individualProducts collection each have a Key and a collection of things that have the same productid.
If you do this directly out of the database, all your operations will get nicely combined into a single SQL statement that will get executed when your code gets to .ToArray()
Related
I think what I need is relatively simple but every example I Google just returns results using First(), which I'm already doing. Here is my expression:
var options = configData.AsEnumerable().GroupBy(row => row["myColumn"]).Select(grp => grp.First());
What I need is only ONE column from the grp portion and to be able to suffix .ToList() on there without an error. As it stands I receive 4 columns, but only need a specific one, kind of like if this (grp => grp["myColumn"]), didn't result in error the Error 153 Cannot apply indexing with [] to an expression of type 'System.Linq.IGrouping<object,System.Data.DataRow>'
Also, Key does not work in the grouping portion as these results are from a DataTable object. See here - >
If you want only the keys, you can use
var options = configData.AsEnumerable().Select(row=>row["myColumn"]).Distinct();
I think that this is what you want:
configData.AsEnumerable()
.GroupBy(r => r["myColumn"])
.Select(g => new
{
myColumnValue = g.Key,
myColumnItems = g.Select(r => r["OtherColumn"]).ToList()
});
Do you understand how/what this does though? Try it out and inspect the resulting IEnumerable. I'm not sure you have a perfect understanding on how GroupBy works but take your time with above example.
See this part:
new
{
myColumnValue = g.Key,
myColumnItems = g.Select(r => r["OtherColumn"]).ToList()
}
This creates an anonymous type which outputs the values of "OtherColumn" column into a list grouped by "myColumn" where value of "myColumn" is in the myColumnValue property.
I'm not sure this answers your question but it looks like this is what you want.
The variable g is of the type IGrouping<object, DataRow>, it's not DataRow. The IGrouping interface is designed to provide a list of DataRow's grouped by object values - it does not produce a flat list, if it did then it would just be a Sort, not GroupBy.
Just specify the field you want after your call to First() e.g.
.Select(grp => grp.FirstOrDefault()["MyFieldName"]);
This will take the first record from the grouping and select the specified field from that record.
This is the problematic code:
var distinctCatNames = allCats.Select(c => c.CatName).Distinct();
if (skip.HasValue) distinctCatNames = distinctCatNames .Skip(skip.Value);
if (take.HasValue) distinctCatNames = distinctCatNames .Take(take.Value);
var distinctCatNameList= distinctCatNames .ToList();
If you imagine I have a list of 100 cats, I want to select the 10 distinct names. It's going into a paged list so it has to use skip and take.
The above won't work, because it has to be ordered with OrderBy.
If I put the OrderBy after the distinct, I can't do Skip and Take because the result is an IOrderedQueryable, not an IQueryable (compiler error).
If I do it before, the error says DbSortClause expressions must have a type that is order comparable.
I need to make sure that under the hood it's translating my query properly, because there may be a lot of cats so I want to ensure it generates SQL that incorporates the skip/take in the query rather than getting ALL cats and then doing it on that collection.
Any ideas?
You need to order the items but then simply type the variable you store it in as an IQueryable, rather than an IOrderedQueryable:
var distinctCatNames = allCats.Select(c => c.CatName)
.Distinct()
.OrderBy(name => name)
.AsQueryable();
I have a need to filter a large collection of objects (in memory) to select only those which meet ALL of the selected categories.
This is essentially the SQL query I'm looking to replicate, but I've been unable to come up with a good C# alternative:
select distinct o.ObjectId
from Object o
join ObjectCategories oc on oc.ObjectId = o.ObjectId
where oc.CategoryId in (1)
and oc.CategoryId in (2)
and oc.CategoryId in (3)
... and so on...
...where 1, 2, and 3 represent the values in an indeterminate number of user-selected categories.
Have your user selected category ID's in a List and then you can use Contains.
select distinct o.ObjectId
from Object o
join ObjectCategories oc on oc.ObjectId = o.ObjectId
where yourCategoryList.Contains(oc=>oc.categoryID);
var results = ObjectCategories.Where(t2 => ObjectList.Any(t1 => t2.Contains(t1)) == true)
you can count the number of matches and if it is equal to the list you are checking against, then you have all the matches.
Consider using Dynamic LINQ. It allows you to use string expressions instead of lambda expressions. You should be able to do what you want using something similar to:
var qry = ObjectCategories.Where(
"ObjectList.CategoryId.Contains(1) AND ObjectList.CategoryId.Contains(2) ..."
);
There is a pretty solid implemention of Dynamic LINQ here: https://github.com/NArnott/System.Linq.Dynamic
I'm trying to write a query that grabs a list of countries out from my joined data.
Places is List<Country>.
var zonedCountries = (from dz in db.DeliveryZones.Include(d => d.Places)
where model.DeliveryZones.Contains(dz.ID)
select dz.Places);
I would expect zonedCountries to be a List but instead it is a IQueryable<ICollection<Country>>.
How do I extract the list from this?
If you want to get flattened list of countries:
var zonedCountries = (from dz in db.DeliveryZones.Include(d => d.Places)
where model.DeliveryZones.Contains(dz.ID)
from p in dz.Places
select p);
Or use SelectMany:
var zonedCountries = db.DeliveryZones.Include(d => d.Places)
.Where(dz => model.DeliveryZones.Contains(dz.ID))
.SelectMany(dz => dz.Places);
BTW I'm not sure if you need to include places manually in this case (thus you are selecting places instead of delivery zones). And you will probably want to select distinct countries only - Distinct() will help you here. Also if you want to store results in list, then simple ToList() call will do the job.
I need to add a literal value to a query. My attempt
var aa = new List<long>();
aa.Add(0);
var a = Products.Select(p => p.sku).Distinct().Union(aa);
a.ToList().Dump(); // LinqPad's way of showing the values
In the above example, I get an error:
"Local sequence cannot be used in LINQ to SQL implementation
of query operators except the Contains() operator."
If I am using Entity Framework 4 for example, what could I add to the Union statement to always include the "seed" ID?
I am trying to produce SQL code like the following:
select distinct ID
from product
union
select 0 as ID
So later I can join the list to itself so I can find all values where the next highest value is not present (finding the lowest available ID in the set).
Edit: Original Linq Query to find lowest available ID
var skuQuery = Context.Products
.Where(p => p.sku > skuSeedStart &&
p.sku < skuSeedEnd)
.Select(p => p.sku).Distinct();
var lowestSkuAvailableList =
(from p1 in skuQuery
from p2 in skuQuery.Where(a => a == p1 + 1).DefaultIfEmpty()
where p2 == 0 // zero is default for long where it would be null
select p1).ToList();
var Answer = (lowestSkuAvailableList.Count == 0
? skuSeedStart :
lowestSkuAvailableList.Min()) + 1;
This code creates two SKU sets offset by one, then selects the SKU where the next highest doesn't exist. Afterward, it selects the minimum of that (lowest SKU where next highest is available).
For this to work, the seed must be in the set joined together.
Your problem is that your query is being turned entirely into a LINQ-to-SQL query, when what you need is a LINQ-to-SQL query with local manipulation on top of it.
The solution is to tell the compiler that you want to use LINQ-to-Objects after processing the query (in other words, change the extension method resolution to look at IEnumerable<T>, not IQueryable<T>). The easiest way to do this is to tack AsEnumerable() onto the end of your query, like so:
var aa = new List<long>();
aa.Add(0);
var a = Products.Select(p => p.sku).Distinct().AsEnumerable().Union(aa);
a.ToList().Dump(); // LinqPad's way of showing the values
Up front: not answering exactly the question you asked, but solving your problem in a different way.
How about this:
var a = Products.Select(p => p.sku).Distinct().ToList();
a.Add(0);
a.Dump(); // LinqPad's way of showing the values
You should create database table for storing constant values and pass query from this table to Union operator.
For example, let's imagine table "Defaults" with fields "Name" and "Value" with only one record ("SKU", 0).
Then you can rewrite your expression like this:
var zero = context.Defaults.Where(_=>_.Name == "SKU").Select(_=>_.Value);
var result = context.Products.Select(p => p.sku).Distinct().Union(zero).ToList();