LINQ Where clause Multiple conditions - sql

Im trying to get all the data rows that contain a certain set of data.
In my database i have some values, including start and length.
I have an array that contains integers called startTimes and another called endTimes.
I need a where clause that would return the records that have a start value contained in startTimes, OR start+length contained in endTimes.
Is there any way to do this?
Thanks
IQueryable<request> proposedRequest = db.requests.Include(r => r.rooms);
proposedRequest = proposedRequest.Where(r=>r.booked.Equals(1));
proposedRequest = proposedRequest.Where(r=>r.roundID.Equals(roundID))8;
proposedRequest = proposedRequest.Where(r=>r.day.Equals(day));
int[] startTimes;
int[] endTimes;
for(var q=0;q<time;q++){
startTimes[startTimes.Length] = time + q;
endTimes[endTimes.Length] = time + q + 1;
}
proposedRequest = proposedRequest.Where(//what goes in here);

i have an array startTime=[1,3,4] and an array endTime=[2,4,5] lets
say. I need to see if any of those values match my records? I dont
think the above would do the job
To check if you have value in Array of int, Use the Contains Method:
proposedRequest = proposedRequest.Where(s => startTimes.Contains(s.INT_ID)
|| endTimes.Contains(s.INT_ID));
Syntax: ARRAY.Contains(ID_TO_SEARCH)
it returns a boolean:
var list = new List<int> {1,2,3,4,5};
var intVar = 4;
var exists = list.Contains(intVar);

will something like this suffice?
var data = collection.Where(
t => startTimes.Contains(t.theTime) ||
endTimes.Contains(t.theTime + theLength));

proposedRequest.Where(pr => startTimesArray.Contains(pr.start) || endTimesArray.Contains(pr.start + pr.length));

Related

how to iterate on selected rows with datables + select extension

I use the select extension an d try to 'alert' with the id of the selected rows.
the following code fails:
let sels = jqTable.api().rows({ selected: true });
let st = '';
sels.each(function (value, index) {
st += ',' + sels.row(value).id();
});
alert(st);
The function is called once independently of selected rows:
0 row: value = [], index = 0
>=1 : value = [0, 2], index = 0
The following code succeeds:
let sels = jqTable.api().rows({ selected: true });
let st = '';
for (let i = 0; i < sels.count(); i++) {
st += ',' + sels.row(sels[0][i]).id();
}
alert(st);
what do I missunderstand with each() :
Iterate over the contents of the API result set.
I notice that the following code runs:
sels.data().each(function (value, index) {
st += ',' + value.IdFile;
});
But using it cancels the advantage of rowId : 'IdFile' in the datatable configuration.
each() is used when the dataset returns an array of results within the API objects - in the case of rows() this isn't the case - it returns a single result, which happen to be an array containing the rowIDs of the selected rows.
Your first code block fails as there's only one iteration (the results are a single array).
Your second block works, because you're iterating over that single array (sels[0]).
And your third also works, as the rows().data() does generate an array containing the data of all the selected rows.
This example will hopefully help!

Use of a string to get information in an associative array

I've got a function that takes two strings as arguments, and I want to use these arguments to get the data held in associative arrays.
var myVar:Object = {};
myVar.value = 10;
function getStuff(v:String, vl:String){
//...
}
In this case, v = "myVar" and vl = "value".
How do I translate vinto the variable name 'myVar' and v1 into 'value' so that I can access the data?
Sorry if this won't work, for I can only test AS3 here, but please try this:
function getStuff(v:String, vl:String){
return eval(v + "." + vl);
}
eventually
function getStuff(v:String, vl:String){
return eval("_gobal." + v + "." + vl);
}

How to sort a List<dynamic> containing ExpandoObjects

I have a list which contains a dictionary of ExpandoObjects. Im binding this to a grid but now I want to sort the list.
var rows = new List<dynamic>();
for (int i = 0; i < 1000; i++)
{
dynamic expandy = new ExpandoObject();
var dictionary = (IDictionary<string, object>)expandy;
dictionary.Add("ID", i);
dictionary.Add("Name", "Name" + i);
rows.Add(dictionary);
}
So looking at the test code above how would I sort rows (ascending or decending) say on "ID" or "Name" or any other property that I dynamically add?
A bit more info, I'm looking to sort it like this (this doesnt work);
var newOrder = from r in rows
orderby ("Name") ascending
select r;
Not sure how I missed this but anyway this works,
var newOrder = rows.OrderByDescending(x => x["Name"]);
WooHoo's answer does not work for Dynamic.ExpandoObject; this works:
var newOrder = rows.OrderByDescending(x =>((IDictionary<string,object>)x)["Name"]);

LINQ & Lambda Expressions equivalent of SQL In

Is there a lambda equivalent of IN? I will like to select all the funds with ids either 4, 5 or 6. One way of writing it is:
List fundHistoricalPrices = lionContext.FundHistoricalPrices.Where(fhp => fhp.Fund.FundId == 5 || fhp.Fund.FundId == 6 || fhp.Fund.FundId == 7).ToList();
However, that quickly becomes unmanageable if I need it to match say 100 different fundIds. Can I do something like:
List
fundHistoricalPrices =
lionContext.FundHistoricalPrices.Where(fhp
=> fhp.Fund.FundId in(5,6,7)).ToList();
It's somewhere along these lines, but I can't quite agree with the approach you have taken. But this will do if you really want to do this:
.Where(fhp => new List<int>{5,6,7}.Contains( fhp.Fund.FundId )).ToList();
You may want to construct the List of ids before your LINQ query...
You can use the Contains() method on a collection to get the equivalent to in.
var fundIds = new [] { 5, 6, 7 };
var fundHistoricalPrices = lionContext.FundHistoricalPrices.Where(fhp => fundIds.Contains(fhp.Fund.FundId)).ToList();
You could write an extension method like this :
public static bool In<T>(this T source, params T[] list)
{
if(null==source) throw new ArgumentNullException("source");
return list.Contains(source);
}
Then :
List fundHistoricalPrices = lionContext.FundHistoricalPrices.Where(fhp => fhp.Fund.FundId.In(5,6,7)).ToList();
No, the only similar operator i'm aware of is the Contains() function.
ANother was is to construct your query dynamically by using the predicate builder out of the LINQkit: http://www.albahari.com/nutshell/predicatebuilder.aspx
Example
int[] fundIds = new int[] { 5,6,7};
var predicate = PredicateBuilder.False<FundHistoricalPrice>();
foreach (int id in fundIds)
{
int tmp = id;
predicate = predicate.Or (fhp => fhp.Fund.FundId == tmp);
}
var query = lionContext.FundHistoricalPrices.Where (predicate);

LINQ: Count number of true booleans in multiple columns

I'm using LINQ to SQL to speed up delivery of a project, which it's really helping with. However I'm struggling with a few things I'm used to doing with manual SQL.
I have a LINQ collection containing three columns, each containing a boolean value representing whether an e-mail, mobile or address is availble.
I want to write a LINQ query to give me an count of trues for each column, so how many rows in the e-mail column are set to true (and the same for the other two columns)
If you need a single object containing the results:
var result = new {
HasEmailCount = list.Count(x => x.HasEmail),
HasMobileCount = list.Count(x => x.HasMobile),
HasAddressCount = list.Count(x => x.HasAddress)
};
Or using the aggregate function:
class Result
{
public int HasEmail;
public int HasAddress;
public int HasMobile;
}
var x = data.Aggregate(
new Result(),
(res, next) => {
res.HasEmail += (next.HasEmail ? 0 : 1);
res.HasAddress += (next.HasAddress ? 0 : 1);
res.HasMobile += (next.HasMobile ? 0 : 1);
return res;
}
);
x is of Type Result and contains the aggregated information. This can also be used for more compelx aggregations.
var mobileCount = myTable.Count(user => user.MobileAvailable);
And so on for the other counts.
You can do it like so:
var emailCount = yourDataContext.YourTable.Count(r => r.HasEmail);
etc.