What's the difference between Where(lambda expr.) and First(lambda expr.) when I need to pick the first item? - linq-to-sql

I'd like to know the difference between this two syntaxes:
return db.Contacts.First(x => x.ContactID == id)
That I've been using so far until I get an error "Sequence contains no elements". then I have to use the below one again.
return db.Contacts.Where(x => x.ContactID == id).First();
There must be a nuance I'm not getting right.
Thanks for helping.

First is used to get the first element of a sequence, but it also takes a predicate to allow you to filter the IEnumerable sequence.
So First will return the first element of an IEnumerable with 1 or more results.
First(Predicate) will return the first element of results within an IEnumerable with 1 or more results.
If there are 0 elements when using First you'll get the error Sequence contains no elements. If you're expecting there to be 0 results, you should use FirstOrDefault. FirstOrDefault can also take a predicate as well, i.e.
// Will return null if there are no elements with a matching contact Id
return db.Contacts.FirstOrDefault(x => x.ContactID == id);

Related

Wrong GridView total rows count

I'm getting a weird result.
In my CustomerQuery i have some filters applied before the all() function.
(like
$this->andWhere(['profiles.type'=>'f']);
)
The filter gets applied before every find()->all(), but in the pagination count before the gridview it states
Showing 1-6 of 12 elements
If i check the query with Yii's debugger, i can see the count query used by yii to determine the number of elements is missing the profiles.type = "f" while the actual query doesn't.
Is this a bug? Is there another function i need to use instead of andWhere to apply the same filter to the count query?
Ok, it seems this in expected result (i'd expect and definitely prefer the count function to execute the exact same query, though).
To apply the same filter/where to both the real query and the count query you have to override the ActiveQuery's count method.
Here's an example
class ProfileQuery extends \yii\db\ActiveQuery{
...
public function standardFilters(){
$this->andWhere(['not',['table_name.status'=>2]]);
}
public function all($db = null){
$this->standardFilters();
return parent::all($db);
}
public function count($q = '*', $db = null) {
$this->standardFilters();
return parent::count($q, $db);
}
...

How to test if collection contains all elements of other collection

With a Set in Ceylon it is straightforward to determine if one collection is a superset of the other. It's just first.superset(second). What's the best way to do the equivalent for an Iterable, List, or Sequential using multiset (or bag) semantics? For example something like the pseudocode below:
{'a', 'b', 'b', 'c'}.containsAll({'b', 'a'}) // Should be true
{'a', 'b', 'b', 'c'}.containsAll({'a', 'a'}) // Should be false
There is Category.containsEvery, which is inherited by Iterable. It checks for each element of the parameter whether it is contained in the receiver, so that bigger.containsEvery(smaller) is equivalent to this:
smaller.every(bigger.contains)
(Note that it is swapped around.) The expression in the brackets here is a method reference, we could also write this expanded with a lambda:
smaller.every(o => bigger.contains(o))
So in your example:
print({'a', 'b', 'b'}.containsEvery({'b', 'a'})); // Should be true
print({'a', 'b', 'b'}.containsEvery({'a', 'a'})); // Should be false
... actually, those both return true. Why do you think the latter one is false?
Did you think of multiset semantics (i.e. the number of occurrences in the "superset" iterable need to be at least as much as the smaller one)? Or do you want a sublist? Or do you just want to know whether the second iterable is at the start of the first (startswith)?
I don't know about any multiset implementation for Ceylon (I found a multimap, though). If you are running on the JVM, you can use any Java one, like from Guava (though that also doesn't have a "contains all with multiples" function, as far as I can see).
For small iterables, you can use .frequencies() and then compare the numbers:
Boolean isSuperMultiset<Element>({Element*} bigger,
{Element*} smaller) =>
let (bigFreq = bigger.frequencies())
every({ for(key->count in smaller.frequencies())
count <= (bigFreq[key] else 0) })
For sublist semantics, the SearchableList interface has the includes method, which checks whether another list is a sublist. (It is not implemented by many classes, though, you would need to convert your first iterable into an Array, assuming it is not a String/StringBuilder.)
For startsWith semantics, you could convert both to lists and use then List.startsWith. There should be a more efficient way of doing that (you just could go through both iterators in parallel).
There is corresponding, but it just stops after the shorter one ends (i.e. it answers the question "does any of those two iterables start with the other", without telling which one is the longer one). Same for a bunch of other pair related functions in ceylon.language.
If you know the length of both of the Iterables (or are confident that .size is fast), that should solve the issue:
Boolean startsWith<Element>({Element*}longer, {Element*}shorter) =>
shorter.size <= longer.size &&
corresponding(longer, shorter);
If you have two Sequentials, then you can remove each right-hand character one at a time from the left-hand sequence until you either remove them all or fail to remove one of them.
Boolean containsAll<Element>([Element*] collection, [Element*] other)
given Element satisfies Object {
variable value remaining = collection;
for (element1 in other) {
value position = remaining.locate((element2) => element1 == element2);
if (exists position) {
remaining = remaining.initial(position.key).append(remaining.spanFrom(position.key + 1));
} else {
// Element was not found in remaining; terminate early
return false;
}
}
// All elements were found
return true;
}
print(containsAll(['a', 'b', 'b', 'c'], ['a', 'b']));
print(containsAll(['a', 'b', 'b', 'c'], ['a', 'a']));
Append only exists on Sequential so it won't work on just a List or an Iterable.
The containsEvery function should do what you want (try it!). Alternatively, you can also turn both streams into sets using the set function (try it!), or use every and contains (try it!).

Conditional inside es6 .map

project im working on used es6/jsx and the airbnb linter but im having some trouble with the following code: i need to map items and compare it to another id but when i write it like this i get an error on the if statement, which is "parsing error unexpected token".
tried parentheses around the item, brackets after fat arrow, but not sure what the issue is. dont need to add return since it knows to expect it back. trying to find the way to get this working with the correct syntax.
const cartItems = items.map(item => {
if (id === item._id) {
console.log('found', item_id);
}
});
edit:
doing it like that, the .map(item has an error: expected parentheses around arrow function having curly braces.
moving over the => { i get an error: expected to return a value in arrow function
and in the console.log the item_id has a error: item._id is not defined, it should have been defined with the map but seems its not seeing it?
basically need to loop through the items id's and match them against another set of ids, if they match i need to combine the matching ones into a new variable
Ive changed it a bit, for what i need by doing it like this:
if (id === items.map(item => item._id)) {
this.setState({ inCart: true });
}
then just use the state value to conditionally load anything i needed.

checking return value of function before using result

placeholder = f()
if placeholder then return placeholder end
this feels inelegant, doing such a simple task in two lines with so many words feels weird. Is there a less verbose/"better" way of writing this?
an example where this is useful is:
for f in pairs(listOfFunctions) do
placeholder = f()
if placeholder then return f() end
end
Background:
a function can have any number of return statements that return any number of values, and can vary from call to call.
or is a selector operator: It returns the first non-"falsey" operand. (These second operand expression is not evaluated unless needed.)
an expression that yields a list preserves the entire list in a list context (for example, the last expression in a list, such a return statement), but only the first value in a non-list context (for example, inside parentheses).
It's unclear which return-lists you want to return and under which conditions. What you are showing appears to be if f() returns a list with a first value neither nil nor false, return that one value; otherwise return an empty list.
But sometimes it doesn't really matter if you return lists with superfluous values, particularly a list of just nil instead of an empty list. Other times, it is useful to return the same number of values every time.
So, here are some alternatives.
Return all values in f()'s result-list
return f()
Or, return only the first value in f()'s result-list, nil if none
return (f())
Or, return the first value in f()'s result-list if it is neither nil nor false, otherwise return nil
return f() or nil
Or, return the first value in f()'s result-list if it is neither nil nor false, otherwise return false
return f() or false
If you find it awkward to have an unconditional return at that point in your code, you would need to restructure your control flow-and might, in fact, benefit from less control-flow anyway.

Create 1 function from 2 other functions in scala?

This question relates to the scala course from coursera so I want to please ask you to not give me the plain solution that I can copy-paste as this would break the coursera honor code.
This relates to the second assignment.
def Set = Int => Boolean
As it can be seen, Set is a function which returns weather or not the given int is or not part of the set. This is plain and simple so far. However the task asks me to create a union
def union(f: Set, s: Set): Set = ???
This union should return a set that satisfies the condition of both sets.
How could I do something like this:
I thought that such a thing could be done by adding the functions together however the following code:
f + s
Will not compile properly as expected
My question to is:
How would I be able to create a function from 2 other functions?
x => if x == 0 true else false //first
x => if x == 1 true else false //second
And what should equal:
x => if x==0 || x == 1 true else false
I'm not asking for a solution but rather how would I go around building something like this?
As I think you already understand, these Sets are functions that test whether a value meets the criteria for each Set.
The union of such a Set must also be a function that returns a Boolean (as shown by the type signature)
def union(f: Set, s: Set): Set
which (because Set is a type alias) is equivalent to:
def union(f: Int => Boolean, s: Int => Boolean): Int => Boolean
In plain English, union of two sets A and B means: "is the item in A or B".
Your task is to write a function that carries out that plain English specification.
You cannot "add" two functions together (at least, not in a way that is applicable to this question), but you can combine their results.
The Set has form of Set = Int => Boolean. Given the Int function will return true if the value is in a Set.
Well if we want to create a singleton set, we will return new function, which will compare any value passed to it, with the one passed to the function that created it.
The union of two sets, is one set plus the other. It means the element you're looking for must be either in one or the other set. But how do we get the new set, well we return a new function that does just that - checks if an element is either in one set or another.
Remember that in Scala functions can return functions, which may be evaluated later. I think that's the key.
The Set is defined as a function from Int to Boolean, "summing" two Sets won't return a Set object, the union means that one element should be either in one or in the other set but always expressed as a function.
I hope this is not too much, but given an element it should satisfy either f or s.
First of all, it's type Set =. Not def. Set is a type alias not a function definition.
Now, your question. You need a function which, when given two Int =>Boolean combines them with OR and returns a Int => Boolean.
First, how would you do this for two Boolean arguments?
def or(a: Boolean, b: Boolean) = a || b
So now we're half way there. What we have:
A pair of Int => Boolean functions.
A function that takes two Booleans and return a Boolean.
So all we need to do is apply each Set to an Int to get a Boolean and OR the result. The confusion is probably here.
The easiest way to curry a function is to do it explicitly
def union(f: Set, s: Set): Set = {
def doUnion(x: Int) = //apply x to f and s, return OR
doUnion
}
But we can, in Scala, so this inline by declaring an anonymous function
def union(f: Set, s: Set): Set = x => //apply x to f and s, return OR