linq EnumerableQuery<Char?>? [closed] - linq

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Any idea how to retrieve the value inside EnumerableQuery I wanna retrieve "Y" or Null for create, update, delete column as the same like I did to Read column, but instead of return "Y" or NULL, it return as EnumerableQuery, and I had no idea how to make it
from a in MenuFunctions
where a.Scd == 'R' && a.Ise == 'Y'
select new{
a.Mcd,
Read = a.Ise,
Create = (from b in MenuFunctions
where b.Pcd== a.Mcd && b.Psc == a.Scd && b.Ise=='Y' && b.Scd =='C'
select b.Ise),
Update = (from b in MenuFunctions
where b.Pcd== a.Mcd && b.Psc == a.Scd && b.Ise=='Y' && b.Scd =='U'
select b.Ise),
Delete = (from b in MenuFunctions
where b.Pcd== a.Mcd && b.Psc == a.Scd && b.Ise=='Y' && b.Scd =='D'
select b.Ise),
}
Result

from a in MenuFunctions
where a.Scd == 'R' && a.Ise == 'Y'
select new{
a.Mcd,
Read = a.Ise,
Create = (from b in MenuFunctions
where b.Pcd== a.Mcd && b.Psc == a.Scd && b.Ise=='Y' && b.Scd =='C'
select b.Ise).firstOrDefault() == null ? "N" : "Y",
Update = (from b in MenuFunctions
where b.Pcd== a.Mcd && b.Psc == a.Scd && b.Ise=='Y' && b.Scd =='U'
select b.Ise).firstOrDefault() == null ? "N" : "Y",
Delete = (from b in MenuFunctions
where b.Pcd== a.Mcd && b.Psc == a.Scd && b.Ise=='Y' && b.Scd =='D'
select b.Ise).firstOrDefault() == null ? "N" : "Y",
}
Ok, I figure it out now, I need to use firstOrDefault to return the value from it
and by adding == null ? "N" : "Y", I also solve the null value inside the column :)
but not sure if any better linq method to perform the same function as this

Related

Xcode slow compile time on equatable protocol

Xcode is taking too long to compile class's with equatable protocol, this is a little strange because in this particular case it's only comparing primitive types, this should be easy.
Took 608ms to type-check this:
public static func == (lhs: TheModel, rhs: TheModel) -> Bool {
return lhs.firstName == rhs.firstName &&
lhs.lastName == rhs.lastName &&
lhs.maritalStatus == rhs.maritalStatus &&
lhs.sex == rhs.sex &&
lhs.birthDate == rhs.birthDate &&
lhs.nationality == rhs.nationality &&
lhs.hasAnotherNationality == rhs.hasAnotherNationality &&
lhs.anotherNationality == rhs.anotherNationality &&
lhs.nif == rhs.nif &&
lhs.hasAnotherFiscalAddress == rhs.hasAnotherFiscalAddress &&
lhs.identificationCard == rhs.identificationCard &&
lhs.identificationCardNumber == rhs.identificationCardNumber &&
lhs.identificationCardExpirationDate == rhs.identificationCardExpirationDate &&
lhs.education == rhs.education &&
lhs.jobTitle == rhs.jobTitle &&
lhs.patronalEntity == rhs.patronalEntity &&
lhs.hasLivesOfIncomes == rhs.hasLivesOfIncomes &&
lhs.permanentAddressContainer == rhs.permanentAddressContainer &&
lhs.fiscalAddressContainer == rhs.fiscalAddressContainer &&
lhs.placeOfBirth == rhs.placeOfBirth &&
lhs.honorificTitle == rhs.honorificTitle &&
lhs.userType == rhs.userType &&
lhs.userTypeDescription == rhs.userTypeDescription &&
lhs.lastVisitedCountryCode == rhs.lastVisitedCountryCode &&
lhs.lastUpdate == rhs.lastUpdate
}
PS:I know this comparison it's a little overkill but it's only an example.
By the way, this was in MacbookPro with core i9, 64Gb of RAM and SSD.
Update - I made some changes and run some more tests:
Test 1
Added explicit type to a let and returned the let: Took ~450ms
public static func == (lhs: TheModel, rhs: TheModel) -> Bool {
let extractedExpr: Bool = lhs.firstName == rhs.firstName &&
lhs.lastName == rhs.lastName &&
lhs.maritalStatus == rhs.maritalStatus &&
lhs.sex == rhs.sex &&
lhs.birthDate == rhs.birthDate &&
lhs.nationality == rhs.nationality &&
lhs.hasAnotherNationality == rhs.hasAnotherNationality &&
lhs.anotherNationality == rhs.anotherNationality &&
lhs.nif == rhs.nif &&
lhs.hasAnotherFiscalAddress == rhs.hasAnotherFiscalAddress &&
lhs.identificationCard == rhs.identificationCard &&
lhs.identificationCardNumber == rhs.identificationCardNumber &&
lhs.identificationCardExpirationDate == rhs.identificationCardExpirationDate &&
lhs.education == rhs.education &&
lhs.jobTitle == rhs.jobTitle &&
lhs.patronalEntity == rhs.patronalEntity &&
lhs.hasLivesOfIncomes == rhs.hasLivesOfIncomes &&
lhs.permanentAddressContainer == rhs.permanentAddressContainer &&
lhs.fiscalAddressContainer == rhs.fiscalAddressContainer &&
lhs.placeOfBirth == rhs.placeOfBirth &&
lhs.honorificTitle == rhs.honorificTitle &&
lhs.userType == rhs.userType &&
lhs.userTypeDescription == rhs.userTypeDescription &&
lhs.lastVisitedCountryCode == rhs.lastVisitedCountryCode &&
lhs.lastUpdate == rhs.lastUpdate
return extractedExpr
}
Test 2
Added parenthesis to each case: Same result as Test 1!
let extractedExpr: Bool = (lhs.firstName == rhs.firstName) &&
(lhs.lastName == rhs.lastName) &&
(lhs.maritalStatus == rhs.maritalStatus) &&
(lhs.sex == rhs.sex) &&
(lhs.birthDate == rhs.birthDate) &&
(lhs.nationality == rhs.nationality) &&
(lhs.hasAnotherNationality == rhs.hasAnotherNationality) &&
(lhs.anotherNationality == rhs.anotherNationality) &&
(lhs.nif == rhs.nif) &&
(lhs.hasAnotherFiscalAddress == rhs.hasAnotherFiscalAddress) &&
(lhs.identificationCard == rhs.identificationCard) &&
(lhs.identificationCardNumber == rhs.identificationCardNumber) &&
(lhs.identificationCardExpirationDate == rhs.identificationCardExpirationDate) &&
(lhs.education == rhs.education) &&
(lhs.jobTitle == rhs.jobTitle) &&
(lhs.patronalEntity == rhs.patronalEntity) &&
(lhs.hasLivesOfIncomes == rhs.hasLivesOfIncomes) &&
(lhs.permanentAddressContainer == rhs.permanentAddressContainer) &&
(lhs.fiscalAddressContainer == rhs.fiscalAddressContainer) &&
(lhs.placeOfBirth == rhs.placeOfBirth) &&
(lhs.honorificTitle == rhs.honorificTitle) &&
(lhs.userType == rhs.userType) &&
(lhs.userTypeDescription == rhs.userTypeDescription) &&
(lhs.lastVisitedCountryCode == rhs.lastVisitedCountryCode) &&
(lhs.lastUpdate == rhs.lastUpdate)
return extractedExpr
Test 3
Added a bollean array as var with explicity type and append each condition: Took 171ms :)
public static func == (lhs: TheModel, rhs: TheModel) -> Bool {
var result: [Bool] = [Bool]()
result.append(lhs.firstName == rhs.firstName)
result.append(lhs.lastName == rhs.lastName)
result.append(lhs.maritalStatus == rhs.maritalStatus)
result.append(lhs.sex == rhs.sex)
result.append(lhs.birthDate == rhs.birthDate)
result.append(lhs.nationality == rhs.nationality)
result.append(lhs.hasAnotherNationality == rhs.hasAnotherNationality)
result.append(lhs.anotherNationality == rhs.anotherNationality)
result.append(lhs.nif == rhs.nif)
result.append(lhs.hasAnotherFiscalAddress == rhs.hasAnotherFiscalAddress)
result.append(lhs.identificationCard == rhs.identificationCard)
result.append(lhs.identificationCardNumber == rhs.identificationCardNumber)
result.append(lhs.identificationCardExpirationDate == rhs.identificationCardExpirationDate)
result.append(lhs.education == rhs.education)
result.append(lhs.jobTitle == rhs.jobTitle)
result.append(lhs.patronalEntity == rhs.patronalEntity)
result.append(lhs.hasLivesOfIncomes == rhs.hasLivesOfIncomes)
result.append(lhs.permanentAddressContainer == rhs.permanentAddressContainer)
result.append(lhs.fiscalAddressContainer == rhs.fiscalAddressContainer)
result.append(lhs.placeOfBirth == rhs.placeOfBirth)
result.append(lhs.honorificTitle == rhs.honorificTitle)
result.append(lhs.userType == rhs.userType)
result.append(lhs.userTypeDescription == rhs.userTypeDescription)
result.append(lhs.lastVisitedCountryCode == rhs.lastVisitedCountryCode)
result.append(lhs.lastUpdate == rhs.lastUpdate)
return !result.contains(false)
}

LINQ to Entities grouped logical operations in Where

I'm trying to execute the following linq query and it seems to be ignoring order of operations. (Parentheses first)
var result = _repo.Transactions.Where(t =>
t.DateEntered > EntityFunctions.AddDays(DateTime.Now, -7)
&& ( t.TranDesc != "BALANCE FORWARD" && t.Withdrawl == 0 && t.Deposit == 0 ) );
Here's the where clause that generates:
WHERE ([Extent1].[dateentered] > (DATEADD (day, -7, SysDateTime())))
AND (N'BALANCE FORWARD' <> [Extent1].[TranDesc])
AND (cast(0 as decimal(18)) = [Extent1].[Withdrawl])
AND (cast(0 as decimal(18)) = [Extent1].[Deposit])
Any ideas what I'm doing wrong?
EDIT:
This is actually what I wanted and it solved my problem. Just didn't think it all the way though. Thanks.
var result = _repo.Transactions.Where(t =>
t.dateentered > EntityFunctions.AddDays(DateTime.Now, -7)
&& ((t.TranDesc == "BALANCE FORWARD" && (t.Withdrawl != 0 || t.Deposit != 0))
|| (t.TranDesc != "BALANCE FORWARD")));
There is no difference between a && (b && c && d) and a && b && c && d, and that's why parentheses within generated SQL are not exactly the same as in your LINQ query. But at the end there is no difference between these queries.

search fails with maxid (ulong.max) and sinceid set, but separately it works

the following query works ok if you comment out either the SinceID or the MaxID clause, but when both are included a "bad url" exception is generated.
var maxId = ulong.MaxValue;
var sinceId = (ulong)341350918903701507;
var searchResult =
(
from search in ctx.Search
where search.Type == SearchType.Search &&
search.ResultType == ResultType.Mixed &&
search.Query == "red wedding" &&
search.SinceID == sinceId &&
search.MaxID == maxId &&
search.IncludeEntities == false &&
search.Count == 200
select search).SingleOrDefault();
If you look at the query result in Fiddler, you'll see that the response is:
{"errors":[{"code":195,"message":"Missing or invalid url parameter"}]}
I can't respond to why Twitter wouldn't accept the query with both SinceID and MaxID. However, the query is formed correctly and there isn't any documentation describing constraints on the relationship between these two parameters for this particular scenario. The purpose of the MaxID is to be the id of the highest tweet to return on the next query. Both MaxID and SinceID are intended to help you page through data. I wrote a blog post on how to do this:
Working with Timelines with LINQ to Twitter
I seem to have the same problem as you are, so the only solution I have was to do it manually, so first I retrieved the the first list setting the sinceId value to the one I have like this:
var searchResult =
(
from search in TwitterCtx.Search
where search.Type == SearchType.Search &&
search.Query == query &&
search.Count == pageSize &&
search.IncludeEntities == true &&
search.ResultType == ResultType.Recent &&
search.SinceID == sinceId
select search
).SingleOrDefault<Search>();
resultList = searchResult.Statuses;
Then I have to search for other tweets (the case when new tweets count is more the pageSize) so I had a while loop like this:
ulong minId = ulong.Parse(resultList.Last<Status>().StatusID) - 1;
List<Status> newList = new List<Status>();
while (minId > sinceId)
{
resultList.AddRange(newList);
searchResult =
(
from search in TwitterCtx.Search
where search.Type == SearchType.Search &&
search.Query == query &&
search.Count == pageSize &&
search.IncludeEntities == true &&
search.ResultType == ResultType.Recent &&
search.MaxID == minId &&
search.SinceID == sinceId
select search
).SingleOrDefault<Search>();
newList = searchResult.Statuses;
if (newList.Count == 0)
break;
minId = ulong.Parse(newList.Last<Status>().StatusID) - 1;
}
Now for some reason here you can use both sinceId and maxId.
Just in case anyone else comes across this, I encountered this issue when the MaxId was an invalid Tweet Id.
I started off using zero but ulong.MaxValue has the same issue. Switch it out with a valid value and it works fine. If you're not using SinceId as well it seems to work fine.
I used to get same error "Missing or invalid url parameter", but as per Joe Mayo's solution, I have additionally added if(sinceID < maxID) condition before do while loop, because the query throws above error whenever maxID is less than sinceID, I think which is incorrect.
if (sinceID < maxID)
{
do
{
// now add sinceID and maxID
searchResponse =
await
(from search in twitterCtx.Search
where search.Type == SearchType.Search &&
search.Query == "from:#" + twitterAccountToDisplay + " -retweets" &&
search.Count == count &&
search.SinceID == sinceID &&
search.MaxID == maxID
select search)
.SingleOrDefaultAsync();
if (searchResponse == null)
break;
if (searchResponse.Count > 0 && searchResponse.Statuses.Count > 0)
{
newStatuses = searchResponse.Statuses;
// first tweet processed on current query
maxID = newStatuses.Min(status => status.StatusID) - 1;
statusList.AddRange(newStatuses);
lastStatusCount = newStatuses.Count;
}
if (searchResponse.Count > 0 && searchResponse.Statuses.Count == 0)
{
lastStatusCount = 0;
}
}
while (lastStatusCount != 0 && statusList.Count < maxStatuses);
//(searchResponse.Count != 0 && statusList.Count < 30);
}

Linq to nHibernate - exclude elements without child elements

var locations = (from location in session.Query<Location>()
where
(location.MB_ID == 0 || location.MB_ID == null) &&
(location.hide != "Y" || location.hide == null) &&
(location.locationNameRaw != "" && location.locationNameRaw != null) &&
((location.isIPCapableText != "" && location.isIPCapableText != null) || (
(location.ISDNNumber1 != null && location.ISDNNumber1 != "") ||
(location.ISDNNumber2 != null && location.ISDNNumber2 != "") ||
(location.ISDNNumber3 != null && location.ISDNNumber3 != "") ||
(location.ISDNNumber4 != null && location.ISDNNumber4 != "") ||
(location.ISDNNumber5 != null && location.ISDNNumber5 != "") ||
(location.ISDNNumber6 != null && location.ISDNNumber6 != "")
))
&& (location.privateRoom == "N" || location.privateRoom == "" || location.privateRoom != null)
&& (
from lll in session.Query<LocationLonLat>()
where
location.locationID == lll.locationId
select lll.locationId
).Any()
&& (location.LastUpdatedTime > lastUpdateTime)
&& location.LocationTimes.Count() > 0
/*&& (
from lt in session.Query<LocationTimes>()
where
location.locationID == lt.LID
select lt.LID
).Any()*/
select location
)
.ToList();
There is a relationship between Location (1) and LocationTimes (many), and I only want to return a dataset of locations that have at least one LocationTime record.
I tried a couple of things...
When I add the line:
&& location.LocationTimes.Count() > 0
or if I add the line:
&& (
from lt in session.Query<LocationTimes>()
where
location.locationID == lt.LID
select lt.LID
).Any()
The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.
I suspect that this may because of the size of the dataset or something...
Is there a better way of doing this? Like with a 'left outer join' or something?
I think a simple join should do it.
from locationTime in Query<LocationTime>()
join location in Query<Location>() on locationTime.Location.LocationId equals location.LocationId
join locationLat in Query<LocationLat>() on location.LocationLat.LocationLatId equals locationLat.LocationLatId
where ...
select location;

help with linq query

i am trying to get some data, but i dont know how can i do a if in linq, this is how i am trying to do
from so in db.Operations
where ((opType!= "0" ? so.Operation == int.Parse(opType) : false)
&& (idState!=0 ? so.State == idState : false)
&& (start != null ? so.StartDate == start : false)
&& (end !=null ? so.EndDate == end : false))
select so
the optype is a Int,
the idState is a Int,
end is a datetime,
start is a datime
what i am trying to do is, if those aren't null they add to the query function, so i can get all data together
for example: in c# code
if((opType!= "0")
where (so.Operation == int.Parse(opType)
if(idState!=0)
where (so.Operation == int.Parse(opType) && so.State == idState
.......
so if that isn't null, that sentence in that sql query (the TRUE part, i dont want to use the false part), add it to the where, so i can search all parameters that aren't null or 0
Since you're &&'ing them, looks like you want : true instead of : false.
Well not sure what you want exactly but here is a try:
var query = db.Operations.AsQueryable();
if (opType != null && opType != "0")
query = query.Where(x => x.Operation == int.Parse(opType);
if (idState != 0)
query = query.Where(x => x.State == idState);
if (start != null) // assuming that start is of type DateTime? otherwise use DateTime.MinValue
query = query.Where(x => x.StartDate.Date == start); // maybe >= is more appropriate
if (end != null) // also DateTime? assumed
query = query.Where(x => x.EndDate.Date == end); // maybe <= is more appropriate
var result = query.ToList(); // e.g. could also do an foreach, depending what you want to do
The trick in this approach is to build up the query successively. The query will not be enumerated until .ToList() or foreach is used to enumerate the list.
Actually this should yield the same:
from so in db.Operations
where ((opType != null && opType!= "0" ? so.Operation == int.Parse(opType) : true)
&& (idState!=0 ? so.State == idState : true)
&& (start != null ? so.StartDate.Date == start : true)
&& (end !=null ? so.EndDate.Date == end : true))
select so
opType!= "0" ? so.Operation == int.Parse(opType) : false
you should not use so.operation == int.parse.... instead use so.operation = int.Parse(opType)
You can use conditional parameters.
Change:
where ((opType!= "0" ? so.Operation == int.Parse(opType) : false)
To:
where ((opType!= "0" ? so.Operation == int.Parse(opType) : so.Operation == Operation)
and so on...

Resources