I have a problem with my code. I don't know how I can insert in my selection all equals conditions of:
codicielementipartizione.sezione == el[i].ToString()
dynamically from
codicielementipartizione.sezione == el[1].ToString()
to
codicielementipartizione.sezione == el[el.count - 1].ToString()
Tn this code:
var selection = (from codicielementipartizione inlistacodici.cep
where codicielementipartizione.uno == 1 &&
codicielementipartizione.sezione == el[i].ToString()
select codicielementipartizione).ToList();
You can make the fixed part of the query which will be IQueryable. After that you can add your conditions as such.
Fixed part:
var query = from codicielementipartizione in listacodici.cep
where codicielementipartizione.uno == 1;
Dynamic part:
foreach(var condition in el)
query = query.Where(codicielementipartizione.sezione == el.ToString());
Query execution:
var result = query.Select().ToList();
Maybe you mean this:
var selection = (from codicielementipartizione in listacodici.cep
where codicielementipartizione.uno == 1
&& el.Select(i => i.ToString()).Contains(codicielementipartizione.sezione)
select codicielementipartizione).ToList();
Related
I wrote a query and worked on LINQPAD
from x in FacilityData
from y in FavInformation
where y.UserID == 1 && x.ID == y.FacilityID
select new
{
xID = x.ID,
xDistrictName = (from y in _Ilcelers
where y.ID == x.DistrictID
select y.IlceAd).FirstOrDefault(),
xName = x.Name,
Value = (from o in Tags
from p in Table_tags
where o.Prefix != null && o.Prefix == p._NAME && o.Facility == y.FacilityID
orderby p.İd descending
select new
{
FType = o.TagType,
Name = o.TagsName,
Value = p._VALUE,
Time = p._TIMESTAMP
}).Take(Tags.Count(h => h.Facility == y.FacilityID))
}
result
the result is perfect
but does not work in visual studio,
Value = (from o in DB.Tags
from p in DB.table_tags
where o.Prefix != null && o.Prefix == p.C_NAME && o.Facility == 11
orderby p.id descending
select new
{
FType=o.TagType,
Name = o.TagsName,
Value = p.C_VALUE,
Time = p.C_TIMESTAMP
}).Take(Tags.Count(h => h.Facility == y.FacilityID))
and it gives an error.
I guess the part with .Take() doesn't work because it's linq to EF.
error:
Limit must be a DbConstantExpression or a Db Parameter Reference Expression. Parametre name: count]
error image
thank you have a good day
Not sure but I will just throw it in. If you are talking about linq to ef/sql, it is possible they dont know a thing about C#. If take() would be the problem try to get the select result local first by doing .tolist(). Afterwards use your take funtion.
.ToList().Take(Tags.Count(h => h.Facility == y.FacilityID))
My Code :
IEnumerable<DataRow> whrRowEnum;
whrRowEnum = from r in dtInput.AsEnumerable()
where r.Field<string>("EMP_DEP") == "DEP1"
orderby EMP_DEP
select r;
The above code is working fine due to hard coded where condition, but In run-time I need to add multiple where condition in my linq query like r.Field("EMP_DEP") == "DEP1" && r.Field("EMP_ID") == "EMP1"
You can use lambda syntax to compose your query based on conditions:
IEnumerable<DataRow> query = dtInput.AsEnumerable();
if (condition1)
query = query.Where(r => r.Field<string>("EMP_DEP") == "DEP1");
if (condition2)
query = query.Where(r => r.Field<string>("EMP_ID") == "EMP1");
var whrRowEnum = query.OrderBy(r => r.Field<string>("EMP_DEP"));
Another option is adding conditions to query filter
whrRowEnum = from r in dtInput.AsEnumerable()
where (!condition1 || (r.Field<string>("EMP_DEP") == "DEP1")) &&
(!condition2 || (r.Field<string>("EMP_ID") == "EMP1"))
orderby EMP_DEP
select r;
my linq query returns duplicate records like below, how i have to use distinct keyword in this linq query.
var draft_recieved = from df in _DataContext.tblDrafts
from dfBody in _DataContext.DraftBodies
from sendUser in _DataContext.tblSends
where (df.DraftId == dfBody.DraftID) && (df.DraftId == sendUser.DraftId) &&
(sendUser.ToEmailId == (Guid)Membership.GetUser().ProviderUserKey)
select new
{
subject = dfBody.Subject,
draftid = df.DraftId
};
.Distinct() has to be applied as an extension method.
var draft_recieved = (from df in _DataContext.tblDrafts
from dfBody in _DataContext.DraftBodies
from sendUser in _DataContext.tblSends
where (df.DraftId == dfBody.DraftID) && (df.DraftId == sendUser.DraftId) &&
(sendUser.ToEmailId == (Guid)Membership.GetUser().ProviderUserKey)
select new
{
subject = dfBody.Subject,
draftid = df.DraftId
}).Distinct();
I have this code:
var query = from deal in db.Deals
where deal.EndDate >= DateTime.UtcNow
select deal;
var priceList = filters.Price.GetPriceRangeList();
foreach(var price in priceList)
{
var startPrice = price.StartPrice;
var endPrice = price.EndPrice;
var priceResult = from deal in query
where (deal.DiscountPrice >= startPrice && deal.DiscountPrice <= endPrice)
select deal;
if(priceResult.Count() != 0)
priceResults = (priceResults == null) ? priceResult : priceResult.Union(priceResults);
}
query = priceResults != null ? query.Intersect(priceResults) : Enumerable.Empty<Deal>().AsQueryable();
My query is slow when priceList has more ten values.
I use Intersect for filters.
How to optimize these queries?
One idea for optimization would be to sort query by StartPrice ascending, that way your inner query can just stop traversal once StartPrice is higher than the DiscountPrice property:
var query = from deal in db.Deals
where deal.EndDate >= DateTime.UtcNow
orderby deal.DiscountPrice ascending
select deal;
..
foreach(..)
{
var startPrice = price.StartPrice;
var endPrice = price.EndPrice;
var queryLocal = query.SkipWhile(deal => deal.DiscountPrice < startPrice);
var priceResult = queryLocal.TakeWhile(deal => deal.DiscountPrice >= startPrice
&& deal.DiscountPrice <= endPrice);
..
}
You have a few issues. The first one is that the query is executed every iteration in your foreach loop. Calling ToList or ToArray will ensure that it is only executed once
Secondly the union is costly. It will iterate priceResult for every iteration of the foreach loop
thirdly your count will also iterate priceResult. Use .Any instead if you wish to know if theres any elements. However I think you can avoid that. If I've read your code correctly I believe the below should have the same result but it does not have the above three issues
var query = (from deal in db.Deals
where deal.EndDate >= DateTime.UtcNow
orderby deal.DiscountPrice ascending
select deal).ToList();
var priceResults = (from price in filters.Price.GetPriceRangeList()
let startPrice = price.StartPrice
let endPrice = price.EndPrice
select query.SkipWhile(d => deal.DiscountPrice < startPrice)
.TakeWhile(d => deal.DiscountPrice <= endPrice)
).SelectMany(x => x);
instead of iterating for each union there's a distinct only once
I've got the following situation:
var totalRecords = (from entry in invalidAccEntryRepository
select entry).Where(entry =>
entry.CustomerAccountInfo.CustomerAccountName == CustomerAccountName &&
entry.CustomerAccountInfo.CustomerAccountId == CustomerAccountId).Count();
vs.
var totalRecords = (from entry in invalidAccEntryRepository
select entry);
if (CustomerAccountInfoFilterActive)
{
totalRecords.Where(entry =>
entry.CustomerAccountInfo.CustomerAccountName == CustomerAccountName &&
entry.CustomerAccountInfo.CustomerAccountId == CustomerAccountId);
}
totalRecordsCount = totalRecords.Count();
The first query works completely but the second query only executes the only
var totalRecords = (from entry in invalidAccEntryRepository
select entry);
and ignores the conditionally added where expression.
Anyone know what the problem could be? Do you need more info?
Thx in advance!
You aren't actually applying the where. In your if, use this instead:
totalRecords = totalRecords.Where(entry =>
entry.CustomerAccountInfo.CustomerAccountName == CustomerAccountName &&
entry.CustomerAccountInfo.CustomerAccountId == CustomerAccountId);