LINQ Method Syntax Basics - c#

I need just some basic help to get me started. I'm doing an assignment for class, and we have to use LINQ method syntax, and I'm really struggling to get anything to work. All I want in this example is to know how to list the Production.SubCategories for a given Production.Category
Any help is greatly appreciated. I just need to get started and I think if I know how to do this I can figure the rest of it out. Online tutorials haven't help me so far...

What you want to do is select a particular property of the ProductCategories model so you can do this:
ProductCategories.Select(pg => pg.ProductSubcategories);
You could also append a .where clause if you wanted to narrow it down

Related

Using C# Linq to query nested objects

I have a PowerShell object and I want to filter the results.
public Collection<PSObject> Groups;
I have successfully achieved this using linq if I need to filter based on a direct member. But what if I want to filter based on an object 1 or 2 levels deep?
Here is the linq query to filter on a direct member:
var groupMembershipFilter = (dynamic)CsQ.Groups.Where(x => x.Members["AgentsByUri"].Value != null).ToList();
However I need to drill down another level. In PowerShell this would be easy:
$x.AgentsByUri.AbsoluteUri
I have tried all sorts but cant figure out how to make this work. So that you can better understand the object structure here are a couple of screen shots:
From the above screen shots you can see the "AgentsByUri" is a collection. Inside that collection I want to test if the property "AbsoluteUri" contains a certain string value.
The other thing I dont understand is why I have to use "Members" and cant just use "BaseObject" - this structure look far more similar to PowerShell and would be my preference if possible as it translates better to my PowerShell brain.
Excuse my terminology, I'm reasonably new to C#! Hopefully this makes sense :)
Any help or guidance would be much appreciated.
Try this:
var groupMembershipFilter = (dynamic)CsQ.Groups.Where(x => x.Members["AgentsByUri"].Any(x => x.AbsoluteUri == "url")).ToList();

Query ContentItems in Orchard

I have a list of 'Article' content items. On this article is an article part, which has a field I'd like to reference in my query.
_contentManager.Query("Article").Where<ArticlePartRecord>(o => o.MyField == "criteria");
The above would work, but I don't have the strongly typed ArticlePartRecord to pass into the Where.
How else can I achieve this?
What I've Tried
I've tried iterating through the parts and fields within the Where, but this would then be done for every single article, of which there could be thousands. It'd pose a few performance problems.
Must I create the type? Or can I pass a string or work around it somehow? If it's a case of creating the class, what fields should this have?
The long and short is that you cant query fields really. Can you move the field into the Article part?
Do you need to be querying or can you use a Projection? There you can query fields because it indexes them all. I suppose you could try to search that index, though I don't believe it exposes it in a very friendly way, but I'm not 100% on that.

Reflection in Linq

This line of code:
db.Set<T>().Max(d => d.GetType().GetProperty("DateTimePropertyName").GetValue(d))
causes this exception:
LINQ to Entities does not recognize the method 'System.Object GetValue(System.Object)' method
How do I make it work?
Your trying to run c# code that's suppose to get translated into SQL somehow and can't.
This is a good guide to start with.
You have two options:
1.Fetch the data from the DB and go through it with LINQ to Objects - Probally the easiest and not the best way to do things since some queries can return large collections.
2.Try to find a better way to do what you are doing. Why would you want this reflection code to run? What's the purpose? Is the DateTimePropertyName non public? If so why? Otherwise something like this should work:
db.Set<T>().Max(d => d.DateTimePropertyName);
By default it assumes that you pass Expression<Func<T,TResult>>, but what you need is to pass Func<T,TResult>:
Func<T, object> f = p => p.GetType().GetProperty("DateTimePropertyName").GetValue(p);
_context.Set<T>().Max(f);
It comes from IEnumerable, so it will hit performance if you table is large

Find index in list of custom objects

I have a list: List<myObject> myList. It currently holds 3 myObjects. Given an int, I need to know how to find the index of any one of those objects so that I can use it elsewhere. I have tried using lambda statements but for some reason they absolutely do not want to work. I'm actually unsure if they're appropriate for this scenario. I have tried using myList's IndexOf, but I can't seem to get that to work, probably because I'm using custom objects.
If anybody can tell me how to accomplish this I would really appreciate it.
how about
var myobject = myList.ToArray()[myInt];
or just
var myobject = myList[myInt];
Try simply this
var myobject = myList[value];
If you can give us some code that would help.
Without any more info, here is something you can try.
int indexFound = Array.IndexOf<myObject>(myList.ToArray(), objectToLocateIdexOf);

Dynamic "WHERE" like queries on memory objects

What would be the best approach to allow users to define a WHERE-like constraints on objects which are defined like this:
Collection<object[]> data
Collection<string> columnNames
where object[] is a single row.
I was thinking about dynamically creating a strong-typed wrapper and just using Dynamic LINQ but maybe there is a simpler solution?
DataSet's are not really an option since the collections are rather huge (40,000+ records) and I don't want to create DataTable and populate it every time I run a query.
What kind of queries do you need to run? If it's just equality, that's relatively easy:
public static IEnumerable<object[]> WhereEqual(
this IEnumerable<object[]> source,
Collection<string> columnNames,
string column,
object value)
{
int columnIndex = columnNames.IndexOf(column);
if (columnIndex == -1)
{
throw new ArgumentException();
}
return source.Where(row => Object.Equals(row[columnIndex], value);
}
If you need something more complicated, please give us an example of what you'd like to be able to write.
If I get your point : you'd like to support users writting the where clause externally - I mean users are real users and not developers so you seek solution for the uicontrol, code where condition bridge. I just though this because you mentioned dlinq.
So if I'm correct what you want to do is really :
give the user the ability to use column names
give the ability to describe a bool function (which will serve as where criteria)
compose the query dynamically and run
For this task let me propose : Rules from the System.Workflow.Activities.Rules namespace. For rules there're several designers available not to mention the ones shipped with Visual Studio (for the web that's another question, but there're several ones for that too).I'd start with Rules without workflow then examine examples from msdn. It's a very flexible and customizable engine.
One other thing: LINQ has connection to this problem as a function returning IQueryable can defer query execution, you can previously define a query and in another part of the code one can extend the returned queryable based on the user's condition (which then can be sticked with extension methods).
When just using object, LINQ isn't really going to help you very much... is it worth the pain? And Dynamic LINQ is certainly overkill. What is the expected way of using this? I can think of a few ways of adding basic Where operations.... but I'm not sure how helpful it would be.
How about embedding something like IronPython in your project? We use that to allow users to define their own expressions (filters and otherwise) inside a sandbox.
I'm thinking about something like this:
((col1 = "abc") or (col2 = "xyz")) and (col3 = "123")
Ultimately it would be nice to have support for LIKE operator with % wildcard.
Thank you all guys - I've finally found it. It's called NQuery and it's available from CodePlex. In its documentation there is even an example which contains a binding to my very structure - list of column names + list of object[]. Plus fully functional SQL query engine.
Just perfect.

Categories

Resources