How to check null in lambda expression - asp.net

How to check for null in where condition in lambda expression?
listdropdownid.Id = listgroupid.Where(X => X.abc == desc).FirstOrDefault().abc_id.ToStr();
listdropdownid.Desc = desc;
If abc == desc fails, I need to assign null to listdropdownid.Id.

The most elegant way is to specify another default value using DefaultIfEmpty(newValue):
listdropdownid.Id = listgroupid
.Where(x => x.abc == desc)
.Select(x => x.abc_id.ToString())
.DefaultIfEmpty(null) // would be more useful if you'd provide a more meaningful value like "<not found>"
.First;
That works even with value types, in this case you could also use FirstOrDefault since the default value of string is already null. You just have to select it:
listdropdownid.Id = listgroupid
.Where(x => x.abc == desc)
.Select(x => x.abc_id.ToString())
.FirstOrDefault();

This should help you:
listdropdownid = listgroupid.Where(X => X.abc == desc).FirstOrDefault();
if (listdropdownid != null)
{
// Do something with listdropdownid.Id
}

do this
listdropdownid.Id = listgroupid.Where(X=>X!=null).Where(X => X.abc == desc).FirstOrDefault().abc_id.ToStr();

Related

In one Linq Query get back data from multiple tables

I have 3 tables:
sessions - This store information about trainings
xref_session_faculty - This cross references the trainings and the teacher
user - list of all teachers
In one(or more) LINQ query i want to get all the sessions and for each session the teachers that will be conducting the training. Each session can have zero or more teachers in the DB.
sessions = db.sessions
.Where(x => x.seminar_id == seminarId)
.ToList()
.Select((x, i) => new fees
{
id = x.id,
sessionTitle = x.title,
teacherNames = "By:" + String.Join(",",
x.xref_session_faculty.ToList()
.Select(q => db.users
.Where(m => m.id == q.user_id)
.Select(t => t.firstName).ToList()
)
)
})
.ToList();
With this the teacherNames prints out By:System.Collections.Generic.List1[System.String],System.Collections.Generic.List1[System.String].
WHat is the right query format here?
teacherNames = "By:" + String.Join(",",
x.xref_session_faculty.ToList()
.Select(q => db.users
.Where(m => m.id == q.user_id)
.Select(t => t.firstName).FirstOrDefault()
)
)
you need to change ToList to FirstOrDefault function to get correct result
private var sessions = (from session in db.sessions.Where(x => x.seminar_id == seminarId)
select new
{
id = session.id,
sessionTitle = session.title,
teacherNames = (from faculty in db.xref_session_faculty.
where (x => x.session_id == session.id)
join us in db.uses on faculty.user_id equals us.user_id
select new
{
us.firstName,
other_field_names
})
});

ASP.NET IQueryable WHERE OR

I am trying to write this piece of code that will search the database table and I am trying to search multiple columns. What I have below appears to be the equivalent to WHERE column = "this" AND column2 = "this", what I am trying to do is this WHERE column = "this" OR column2 = "this" How would I accomplish this?
query = query.Where(p => (p.ChckNumber.ToString()).Contains(globalSearch.ToString()));
query = query.Where(p => (p.BankAccount.ToString()).Contains(globalSearch.ToString()));
query = query.Where(p => (p.Description.ToString()).Contains(globalSearch.ToString()));
query = query.Where(p => (p.CheckAmount.ToString()).Contains(globalSearch.ToString()));
query = query.Where(p => (p.ClearedDate.ToString()).Contains(globalSearch.ToString()));
query = query.Where(p => (p.SentDate.ToString()).Contains(globalSearch.ToString()));
You should be able to do this in-line using the OR operator:
query = query.Where(p =>
p.ChckNumber.ToString().Contains(globalSearch.ToString()) ||
p.BankAccount.ToString().Contains(globalSearch.ToString()) ||
p.Description.ToString().Contains(globalSearch.ToString()) ||
p.CheckAmount.ToString().Contains(globalSearch.ToString()) ||
p.ClearedDate.ToString().Contains(globalSearch.ToString()) ||
p.SentDate.ToString().Contains(globalSearch.ToString())
);

using select in datatable

My Datatable is in following format.
I want to get the Netfare Where Sector is 1 and then similarly I want to get Netfare Where Sector is 2.
Thanks
You can use the DataTable.Select method to filter the result.
var sector1Results = dt.Select("Sector = 1");
var sector2Results = dt.Select("Sector = 2");
You can also use DataTable.AsEnumerable method to achieve the same
var result1 = dt.AsEnumerable().Where(x => x.Field<int>("Sector") == 1).Select(x => x.Field<int>("Sector1"));
var result2 = dt.AsEnumerable().Where(x => x.Field<int>("Sector") == 2).Select(x => x.Field<int>("Sector2"));
To select the DataRow collection, You can use this
List<DataRow> collection1 = dt.AsEnumerable().Where(x => x.Field<int>("Sector") == 1).ToList();
List<DataRow> collection2 = dt.AsEnumerable().Where(x => x.Field<int>("Sector") == 1).ToList();
You can also merge those condition in single statement (if you want)
List<DataRow> collection = new DataTable().AsEnumerable().Where(x => x.Field<int>("Sector") == 1 || x.Field<int>("Sector") == 2).ToList();

LINQ query not equal

Afternoon,
How would i set this as not equal to? I am basically trying to say, if p.catrgory is not equal to one of the categories in the database.
p.category == dc.Categories.SingleOrDefault(c => c.Name == p.category).Name
Thanks in advance
p.Category is not in the DB?
var exists == !dc.Categories.Any(c => c.Name == p.category)
dc.Categories.Where(c => c.Name = p.category).Any();
it will return true if exists, so, use, ! operator
!dc.Categories.Where(c => c.Name = p.category).Any();
You should change:
p.category == dc.Categories.SingleOrDefault(c => c.Name == p.category).Name
to
p.category == dc.Categories.SingleOrDefault(c => c.Name != p.category).Name
if p.category is not equal to one of the categories in the databas

Dynamic Linq for dates

I want to build dynamic Linq. Following is my code which works fine for one date. But user can select many dates from calendar. And I need to make Linq for all those selected dates.
saleDate = calendarSales.SelectedDate;
List<SaleDetails> saleDetials = new List<SaleDetails>();
saleDetials = GetSaleDetails();
saleDetials.Where(sale => (Convert.ToDateTime(sale.DATE_TIME).Day == saleDate.Day &&
Convert.ToDateTime(sale.DATE_TIME).Month == saleDate.Month &&
Convert.ToDateTime(sale.DATE_TIME).Year == saleDate.Year)
).ToList();
How to update this query?
You have to build the predicate for your where clause dynamically.
Take a look at the predicatebuilder.
EDIT
Of cause PredicateBuilder supports AND and OR operators.
When using OR you have to start with the initial value of False:
// building the predicate
var pred = PredicateBuilder.False<SaleDetails>();
foreach (var date in MyDateList)
{
pred = pred.Or(sale => sale.DATE_TIME.Date == saleDate.Date);
}
// finally get the data and filter it by our dynamic predicate
List<SaleDetails> saleDetails = GetSaleDetails().Where(pred).ToList();
I'm not sure you need dynamic LINQ here. You should be able to check Where the sale matches Any of the selected dates, like so:
var saleDates = GetSelectedDate();
List<SaleDetails> saleDetials = new List<SaleDetails>();
saleDetials = GetSaleDetails();
saleDetials.Where(sale => saleDates.Any(date =>
(Convert.ToDateTime(sale.DATE_TIME).Day == date.Day &&
Convert.ToDateTime(sale.DATE_TIME).Month == date.Month &&
Convert.ToDateTime(sale.DATE_TIME).Year == date.Year)
)).ToList();
or checking on the Date property:
var saleDates = GetSelectedDate();
List<SaleDetails> saleDetials = new List<SaleDetails>();
saleDetials = GetSaleDetails();
saleDetials.Where(sale => saleDates.Any(date =>
Convert.ToDateTime(sale.DATE_TIME).Date == date.Date)).ToList();

Resources