How can i use select to string in linq? - c#

How cani use below codes string id = ( from in .....) how?
using (StockProcedureDataContext stock = new StockProcedureDataContext())
{
id = (from m in stock.StockTools
from ss in stock.RefStockStatus
where (m.statusid == 3 || m.statusid == 5) &&
ss.id == m.statusid && m.id == ItemID
select m.id);
How can i do above wthout using below?
id = (from m in stock.StockTools
from ss in stock.RefStockStatus
where (m.statusid == 3 || m.statusid == 5) &&
ss.id == m.statusid && m.id == ItemID
select m).ToList()[0].id;

query.Single()
That's it.

id = (from m in stock.StockTools
from ss in stock.RefStockStatus
where (m.statusid == 3 || m.statusid == 5) &&
ss.id == m.statusid && m.id == ItemID
select m.id).FirstOrDefault();

if you want to retrieve a single result user FirstOrDefault() or First().
If you use First() and the result is null.It will throws exception but not in FirstOrDefault().
var query = (from m in stock.StockTools
from ss in stock.RefStockStatus
where (m.statusid == 3 || m.statusid == 5) &&
ss.id == m.statusid && m.id == ItemID
select m.id).FirstOrDefault();

Just for variety...
query.Take(1)

Related

Prevent Entity Framework query from being evaluated locally

I have this query that is being partially evaluated locally and I am wondering how to prevent it.
It seems to be the conditional select that is causing the problem.
var fetchQuery = (
from udg in _entities.UberDirectGroups.AsNoTracking()
join uber in _entities.Ubers.AsNoTracking()
on udg.Id equals uber.Id
let memberCount = (
from t in _entities.UberDirects.AsNoTracking()
join u in _entities.Ubers.AsNoTracking()
on t.UberToId equals u.Id
where t.UberFromId == udg.Id && !u.Deleted
select u.UberTypeId == (byte)UberType.User ? 1 :
u.UberTypeId == (byte)UberType.Department ? u.Department.Users.Where(user => user.Deleted == false).Count() :
u.UberTypeId == (byte)UberType.Office ? u.tblOffice.tblDepartment.SelectMany(d => d.Users).Where(user => user.Deleted == false).Count() :
u.UberTypeId == (byte)UberType.ProjectGroup ? u.Group.GroupMembers.Select(pm => pm.User).Where(user => user.Deleted == false).Count() :
u.UberTypeId == (byte)UberType.Role ? _entities.Roles.Where(r => r.RoleDataId == u.tblRoleData.Id).Select(r => r.tblUser).Where(user => user.Deleted == false).Count() : 0
).Sum()
where
udg != null &&
uber != null &&
uber.InstanceId == instanceId &&
(!isSearch || udg.Name.Contains(searchText))
select new TargetGroupProjection
{
id = udg.Id,
name = udg.Name,
created = uber.Date,
toCount = memberCount
}
);

Shortening loop to one QUERY in LINQ

Below is a piece of code that I do in a loop:
At the beginning, in the first query, I get a list of location IDs. The list can be long.
Ultimately, I need to find for which LocationId FamiliId > 0
I have it done in a loop but I would like to do it in one question. Is it possible and if so how?
var locationIds = context.TblUsersDistricts
.Where(d => d.UserId == userId && d.ValidityTo == null)
.Select(x => x.LocationId).ToList();
int familyId = 0;
foreach(var item in locationIds) {
familyId = (from I in context.TblInsuree
join F in imisContext.TblFamilies on I.FamilyId equals F.FamilyId
join V in imisContext.TblVillages on F.LocationId equals V.VillageId
join W in imisContext.TblWards on V.WardId equals W.WardId
join D in imisContext.TblDistricts on W.DistrictId equals D.DistrictId
where(I.Chfid == chfid &&
D.DistrictId == item &&
F.ValidityTo == null &&
I.ValidityTo == null &&
V.ValidityTo == null &&
W.ValidityTo == null &&
D.ValidityTo == null)
select F.FamilyId)
.FirstOrDefault();
if (familyId > 0) break;
};
It sounds like you want:
var familyId = (
from item in locationIds
from I in context.TblInsuree
// ... etc
&& D.ValidityTo == null)
select F.FamilyId)
.FirstOrDefault();
?

If else condition in multiple from in LINQ in C#

I have linq query where I need to set condition if p.conditionVariable > 0 I would apply the following condition.
from prob in table2.where(p => p.Id == p.ConditionVariable && !p.IsBlocked && p.IsActive)
if p.conditionVariable == 0 the following remains the same.
(from _obj1 in table1.Where(p => p.IsActive == true))
from prob in table2.Where(p => p.Id == _obj1.Id && !p.IsBlocked && p.IsActive && p.ConditionVariable == 0)
select new Class1
{
Title = prob.Title,
Status = prob.IsPending,
Id = obj1.id
}
I think you want to make a || between conditions and table2 will be queried based on p.CondtionVariable.
(from _obj1 in table1.Where(p => p.IsActive == true))
from prob in table2.Where(p => (p.Id == _obj1.Id && !p.IsBlocked && p.IsActive && p.ConditionVariable == 0)
|| (p.ConditionVariable > 0 && p.Id == p.ConditionVariable && !p.IsBlocked && p.IsActive))
select new Class1
{
Title = prob.Title,
Status = prob.IsPending,
Id = _obj1.id
}
If you want to use if/else conditions, you can use something like this
(from _obj1 in table1.Where(p => p.IsActive == true))
from prob in table2.Where(p => {
bool state = false;
if(p.ConditionVariable > 0) {
state = p.Id == p.ConditionVariable && !p.IsBlocked && p.IsActive;
} else if(p.ConditionVariable == 0) {
state = p.Id == _obj1.Id && !p.IsBlocked && p.IsActive;
}
return state;
})
select new Class1
{
Title = prob.Title,
Status = prob.IsPending,
Id = _obj1.id
}
I would put the p.ConditionVariable test at the beginning so taht it is the first thing checked (as && operations stop at the first failing condition. IF the first check fails then the || operation is checked next):
(from _obj1 in table1.Where(p => p.IsActive == true))
from prob in table2.Where(
(p => p.ConditionVariable == 0 && p.Id == _obj1.Id && !p.IsBlocked && p.IsActive)
|| (p.ConditionVariable > 0 && p.Id == p.ConditionVariable && !p.IsBlocked && p.IsActive))
select new Class1
{
Title = prob.Title,
Status = prob.IsPending,
Id = obj1.id
}
A second variant would also be possible with myvariable=0 ? .... as someone commented but in this case it is not really necessary as you have the || && operators there anyway.

Where clause after String.Join in Linq to Entites

I have a Linq to Entites query where I have implemented the logic. But, I have done the query where clause performs after string join. BTW, I need to know how can I join the string first before doing the where filter. When I execute the query where clause after the string join, it takes so long to filter the records. Since my database have nearly 2 lakh sample records.
Here is my query what I am looking for:
// But the below query throws string join cannot be converted to store expression.
var NewBibContentsModel = (from x in db.BibContents
where (x.TagNo == "245" && string.Join(" ", x.NormValue) == aa.CurrentTitle) || ((x.TagNo == "020") || (x.TagNo == "022") && string.Join(" ", x.NormValue) == aa.CurrentISBN)
select new
{
BibId = x.BibId,
Title = (from a in db.BibContents where a.BibId == x.BibId && a.TagNo == "245" orderby a.Id ascending select a.NormValue),
Author = (from a in db.BibContents where a.BibId == x.BibId && splitted.Contains(a.TagNo) && a.NormValue != null select a.TagNo).FirstOrDefault(),
ISBN = (from a in db.BibContents where a.BibId == x.BibId && a.NormValue != null && (a.TagNo == "020" || a.TagNo == "022") orderby a.Id ascending select a.NormValue)
}).AsEnumerable().Select(x => new BibContentsModel
{
BibId = x.BibId,
Title = string.Join(" ", x.Title),
Author = string.Join(" ", (from a in db.BibContents where a.BibId == x.BibId && a.TagNo == x.Author orderby a.Id select a.NormValue)),
ISBN = string.Join(" ", x.ISBN),
RRId = aa.RRId
}).ToList();
Query with Where clause after string Join
// The below query takes so much of time to filter the records.
var NewBibContentsModel = (from x in db.BibContents
select new
{
BibId = x.BibId,
Title = (from a in db.BibContents where a.BibId == x.BibId && a.TagNo == "245" orderby a.Id ascending select a.NormValue),
//Tit = (from a in db.BibContents where a.BibId == line.BibId && a.TagNo == "245" && a.Sfld == "a" select a.NormValue).FirstOrDefault(),
Author = (from a in db.BibContents where a.BibId == x.BibId && splitted.Contains(a.TagNo) && a.NormValue != null select a.TagNo).FirstOrDefault(),
ISBN = (from a in db.BibContents where a.BibId == x.BibId && a.NormValue != null && (a.TagNo == "020" || a.TagNo == "022") orderby a.Id ascending select a.NormValue)
}).AsEnumerable().Select(x => new BibContentsModel
{
BibId = x.BibId,
Title = string.Join(" ", x.Title),
Author = string.Join(" ", (from a in db.BibContents where a.BibId == x.BibId && a.TagNo == x.Author orderby a.Id select a.NormValue)),
ISBN = string.Join(" ", x.ISBN),
RRId = aa.RRId
}).Where (x=> x.Title == aa.CurrentTitle || (x.ISBN == aa.CurrentISBN)).ToList();
Any help or suggestion to this problem will be appreciated.
Thanks,

linq to entities nested select fillout

I'm trying to return a result and a nested result in a linq to entities query.
Orders[] orderlist =
(from m in db.Orders.Include("OrderLines")
where
areas.Contains(m.Area)
&& m.Branch == branch
&& (m.OrderStatus == "1" || m.OrderStatus == "4")
&& m.SpecialInstrs == string.Empty
select m
HOW??---> m.OrderLines = m.OrderLines.Where(p => (p.LineType == "1" || p.LineType == "7") && p.MBomFlag != "C").ToArray()
).ToArray();
The problem is that the include returns all the FK'd OrderLines for each order when I really only want certain order lines.
How do I do this?
Orders and OrderList are both POCO entities generated by L2E and the poco entity generator.
You can manually join them:
Orders[] orderlist = (from m in db.Orders
join p in db.Orderlines
on p.OrderId = m.Id
where areas.Contains(m.Area)
&& m.Branch == branch
&& (m.OrderStatus == "1" || m.OrderStatus == "4")
&& m.SpecialInstrs == string.Empty
&& (p.LineType == "1" || p.LineType == "7")
&& p.MBomFlag != "C"
select m).ToArray();

Categories