Convert linq expression from method syntax to query syntax - linq

Well I've got a query
var grouped = from a in query
group a.Payment by a.PaymentRecieverId
into g
select g;
query is a IQueryable of new { Payment payment, int PaymentRecieverId }
How can I convert this method expression to query?

If I understand correctly, the question is how to map group a.Payment part.
The GroupBy method has several overloads, you need the one that allows you to specify elementSelector:
var grouped = query.GroupBy(a => a.PaymentRecieverId, a => a.Payment);

If you mean lambda syntax, then it will be:
var grouped = query.GroupBy(x => x.PaymentRecieverId);
If you mean SQL query, then just hover your mouse on query object while debugging:

Related

Get min DateTime from Linq

How can I convert this linq query to single line?
var closets = (from v in options
select v.ExceriseDate).Min();
var option = options.Where(v => v.ExceriseDate == closets).Single();
return option;
Like so:
options.OrderBy(v => v.ExceriseDate).First();
I'll also add that you don't want to use Single() unless you can guarantee it will be unique. It will throw an exception if more than one exist. That would happen if two if your objects shared the same ExceriseDate. Lastly if you prefer the query syntax for Linq over the expression method:
var option = (from v in options
orderby v.ExceriseDate
select v).First();

Dynamic Linq on DataTable error: no Field or Property in DataRow, c#

I have some errors using Linq on DataTable and I couldn't figure it out how to solve it. I have to admit that i am pretty new to Linq and I searched the forum and Internet and couldn't figure it out. hope you can help.
I have a DataTable called campaign with three columns: ID (int), Product (string), Channel (string). The DataTable is already filled with data. I am trying to select a subset of the campaign records which satisfied the conditions selected by the end user. For example, the user want to list only if the Product is either 'EWH' or 'HEC'. The selection criteria is dynaically determined by the end user.
I have the following C# code:
private void btnClick()
{
IEnumerable<DataRow> query =
from zz in campaign.AsEnumerable()
orderby zz.Field<string>("ID")
select zz;
string whereClause = "zz.Field<string>(\"Product\") in ('EWH','HEC')";
query = query.Where(whereClause);
DataTable sublist = query.CopyToDataTable<DataRow>();
}
But it gives me an error on line: query = query.Where(whereClause), saying
No property or field 'zz' exists in type 'DataRow'".
If I changed to:
string whereClause = "Product in ('EWH','HEC')"; it will say:
No property or field 'Product' exists in type 'DataRow'
Can anyone help me on how to solve this problem? I feel it could be a pretty simple syntax change, but I just don't know at this time.
First, this line has an error
orderby zz.Field<string>("ID")
because as you said, your ID column is of type int.
Second, you need to learn LINQ query syntax. Forget about strings, the same way you used from, orderby, select in the query, you can also use where and many other operators. Also you'll need to learn the equivalent LINQ constructs for SQL-ish things, like for instance IN (...) is mapped to Enumerable.Contains etc.
With all that being said, here is your query
var productFilter = new[] { "EWH", "HEC" };
var query =
from zz in campaign.AsEnumerable()
where productFilter.Contains(zz.Field<string>("Product"))
orderby zz.Field<int>("ID")
select zz;
Update As per your comment, if you want to make this dynamic, then you need to switch to lambda syntax. Multiple and criteria can be composed by chaining multiple Where clauses like this
List<string> productFilter = ...; // coming from outside
List<string> channelFilter = ...; // coming from outside
var query = campaign.AsEnumerable();
// Apply filters if needed
if (productFilter != null && productFilter.Count > 0)
query = query.Where(zz => productFilter.Contains(zz.Field<string>("Product")));
if (channelFilter != null && channelFilter.Count > 0)
query = query.Where(zz => channelFilter.Contains(zz.Field<string>("Channel")));
// Once finished with filtering, do the ordering
query = query.OrderBy(zz => zz.Field<int>("ID"));

How to add a second where clause to a linq expression

Trying to add a second where clause to a linq expression but it won't register.
var query = _dbSetBookedResource.AsQueryable<Resource>();
var resources = (from Resource in query where Resource.DateFrom == date select Resource)
if(true)
{
resources.Where(b => b.MemberId == currentUserId);
}
For some reason the second where clause won't register.
For some reason the second where clause won't register.
That's because you're not using the return value anywhere. That's just setting up a query, but then ignoring it. No LINQ methods change the value they're called on - instead they create a new query which has the appropriate filtering, projection etc.
You need:
resources = resources.Where(b => b.MemberId == currentUserId);
Also note that your initial query could be written more simply as:
var resources = query.Where(r => r.DateFrom == date);
Query expressions are overkill when all you want is a simple filter or projection.

Convert IQueryable to List<T> type

I just performed a query with LINQ from the DAL and got a collection of a record with imbedded ILIST objects like the following
string name
date startDate
date endDate
ILIST<MyType> ImbeddedList (this contains more columns like recordID, sentDate, dueDate)
I need to return a LIST<T> back to the grid to be bounded.
I am having some problems with writing the LINQ statement to filter out the IQueryable collection object.
In my statement below:
IQueryable<All_DATA> cases = dalObject.GetData();
var mylist = cases.Select(s => {s.name, s.startDate, s.endDate,s.ImbeddedList????}).ToList();
When I get to the ImbeddedList, which is returned from the dalObject, the intellsense does not show the fields in the ImbeddedList. How can I correctly write the LINQ statement to filter for more fields in the ImbeddedList object?
As far I understand what you can do is
For fetching complete list from ImbeddedList
var mylist = cases.Select(s => {s.name, s.startDate, s.endDate, s.ImbeddedList}).ToList();
And for fetching individual field from ImbeddedList
var mylist = cases.SelectMany(s => s.ImbeddedList)
.Select(IItem => { IItem.Field1, IItem.Field2 }).ToList();
For more information please refer:
The Linq SelectMany Operator
LINQ - Get all items in a List within a List?
Using LINQ, select list of objects inside another list of objects
Use Google Search: "linq select list within list"

How do I use Like in Linq Query?

How I can use Like query in LINQ ....
in sql for eg..
name like='apple';
thanks..
Use normal .NET methods. For example:
var query = from person in people
where person.Name.StartsWith("apple") // equivalent to LIKE 'apple%'
select person;
(Or EndsWith, or Contains.) LINQ to SQL will translate these into the appropriate SQL.
This will work in dot notation as well - there's nothing magic about query expressions:
// Will find New York
var query = cities.Where(city => city.Name.EndsWith("York"));
You need to use StartsWith, Contains or EndsWith depending on where your string can appear. For example:
var query = from c in ctx.Customers
where c.City.StartsWith("Lo")
select c;
will find all cities that start with "Lo" (e.g. London).
var query = from c in ctx.Customers
where c.City.Contains("York")
select c;
will find all cities that contain "York" (e.g. New York, Yorktown)
Source
name.contains("apple");
I use item.Contains("criteria"), but, it works efficiently only if you convert to lower both, criteria and item like this:
string criteria = txtSearchItemCriteria.Text.ToLower();
IEnumerable<Item> result = items.Where(x => x.Name.ToLower().Contains(criteria));

Resources