lambda expression for multiple countries in Linq to Entity - linq

I have a field called Country.
Now I have to filter the records based on the matching country.
When I have to filter the records for single country i use the lambda expression as below.
string strCountry = "USA";
var data = entities.Documents.Where(p => p.Country == strCountry);
Now I have the list of countries as below. I am wondering how to filter the records for this Contry List.
List<string> strCountry = new CacheUser().GetUserCountry();
Appreciate your responses.
Thanks

Try:
List<string> countries = ...;
var data = entities.Documents.Where(p => countries.Contains(p.Country));
This should result in an "IN" query in SQL. However, you should be aware that this may fail once you get a large number of countries in the list. I assume you can't do this with a join instead? The list of countries is only known at the client side?

Related

Convert linq expression from method syntax to query syntax

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:

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"));

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"

Best way to get individual days from a column, using LINQ

I have the following data in one MSSQL Table column
2011-06-20 11:53:32.000
2011-06-20 11:54:24.000
2011-06-20 11:55:45.000
2011-08-05 10:24:12.000
2011-08-05 10:25:28.000
2011-08-05 10:26:20.000
2011-08-05 10:27:12.000
2011-08-05 10:28:04.000
2011-08-05 10:28:55.000
Using LINQ, I would like to get the following data from the column
2011-06-20
2011-08-05
So I can put into a List<>
What's the best way to do this? I already have the context stuff setup, so I don't need details on that. I just need an idea of the best "query" and logic I can use to get this data. Thanks!
You are looking for all of the Distinct dates in a range of DateTimes, the following will show examples to get what you need, given you already have them in a string or by querying your database:
Example (with list of strings):
var list; //Contains your dates
var result = list.Select(x => x.Date.ToShortDateString()).Distinct();
Example (from database table):
List<String> dates = (FROM d in datesTable
SELECT d.date.ToShortDateString()).Distinct().ToList();
Console Example to demonstrate functionality:
List<DateTime> list = new List<DateTime>();
list.Add(DateTime.Parse("2011-06-20 11:53:32.000"));
list.Add(DateTime.Parse("2011-05-20 11:53:32.000"));
list.Add(DateTime.Parse("2011-05-20 11:44:32.000"));
list.Add(DateTime.Parse("2011-04-20 11:53:32.000"));
var result = list.Select(x => x.Date.ToShortDateString()).Distinct();
foreach (string date in result)
{
Console.WriteLine(date);
}
Console.Read();
var q = from t in mydates select distinct ( t.Date.ToShortDateString());
To select distinct dates into a list try this:
List<String> myDates = (from t in myTable
select t.myDate.ToShortDateString()
).Distinct().ToList()

Can we filter Datatable with LINQ?

Suppose my datatable is filled with data.
After filling data can we again put some condition on datatable with linq to extract data.
Suppose my datatable has 10 employee record.
So can we extract only those employee whose salary is greater than 5000 with linq query.
I know that we can achieve it datatable.select(). How can you achieve this with linq?
You can get a filtered set of rows, yes:
var query = table.AsEnumerable()
.Where(row => row.Field<decimal>("salary") > 5000m);
This uses the AsEnumerable and Field extension methods in DataTableExtensions and DataRowExtensions respectively.
Try this:
var query = (from t0 in dtDataTable.AsEnumerable()
where t0.Field<string>("FieldName") == Filter
select new
{
FieldName = t0.Field<string>("FieldName"),
FieldName2 = t0.Field<string>("FieldName2"),
});

Resources