This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Shorthand conditional in C# similar to SQL 'in' keyword
I have a string variable which holds states. I want to check whether it equals to one of these three. I want it to work the way IN works in SQL Server. IS it possible to do with Linq to Objects.
i want
if(str IN ("WA","CA","CO"))
{
}
else
{
}
How to do it. I donot want to use multiple OR conditions.
unfortunately there is no IN, but you can say this
if (new[] { "WA", "CA", "CO" }.Contains(str))
{
}
It seems the wrong way around but it's the best we've got.
How about
if ((new string [] {"WA", "CA", "CO"}).Contains(str))
{
}
else
{
}
This is using the .Contains() extension method on IEnumerable<> - not full LINQ but it should work. In production code you'd want to extract the array
new string[] {"WA", "CA", "CO"}
out to a local field.
You can make an extension method:
public static class Extensions {
public static bool In<T>(this T value, params T[] options) : where T : IComparable<T> {
foreach (T option in options) {
if (value.CompareTo(option) == 0) return true;
}
return false;
}
}
Usage:
var result = someCollection.Where(x => x.Property.In(1,2,3));
Related
As i am working in a Project where i want to rewrite the Uni to Multi for a method "findall" to get all the mongodb Document from a collection. I tried to rewrite but not able to find a solution
original:
public Uni<List<Book>> findAll(List<String> authors)
{
return getCollection().
find(Filters.all("authors",authors)).map(Book::from).collectItems().asList();
}
What i tried (But not working)
public Multi<Book> findAll(List<String> authors)
{
return getCollection().find(Filters.all("authors",authors)).transform().
byFilteringItemsWith(Objects::nonNull).onCompletion().ifEmpty().
failWith(new NoSuchElementException("couldn't find the Authors")).onItem().transform(Book::from);
}
I suppose you are using the ReactiveMongoClient provided by Quarkus.
In this case, your method should be:
ReactiveMongoClient client;
public ReactiveMongoCollection<Book> getCollection() {
return client.getDatabase("db").getCollection("books", Book.class);
}
public Multi<Book> findAll(List<String> authors) {
return getCollection()
.find(Filters.all("authors",authors))
.onItem().transform(Book::from)
.onCompletion().ifEmpty()
.failWith(new NoSuchElementException("..."));
}
You don't need to do thebyFilteringItemsWith, as a Multi cannot contain null items.
I'm running into an issue with coffeescript where I would like to be able to use the ecmascript get and set keywords, however the syntax doesn't make sense in coffeescript.
Here's an example of the original javascript
// A Tutorial class that takes a document in its constructor
Tutorial = function (id, name, capacity, owner) {
this._id = id;
this._name = name;
this._capacity = capacity;
this._owner = owner;
};
Tutorial.prototype = {
get id() {
// readonly
return this._id;
},
get owner() {
// readonly
return this._owner;
},
get name() {
return this._name;
},
set name(value) {
this._name = value;
},
get capacity() {
return this._capacity;
},
set capacity(value) {
this._capacity = value;
}
};
And here's an example of my best guess of what that might translate into:
class Question
constructor: (id, #name, #capacity, #owner) ->
#_id = id
Question::get id() ->
return #_id
however that of course doesn't actually compile to anything useful.
I've seen a few examples of work arounds, but I guess the real question is whether there is any support for this at all in Coffescript directly?
I don't think Coffeescript does support getter/setter declaration in object literals at all. It's been discussed multiple times, see issues 64, 451, 322, 2878:
In summary: we explicitly ignore the existence of setters/getters because we consider them a bad part of JS
The best workaround you can get is
Object.defineProperty Question::, "id",
get: -> #_id
enumerable: true
configurable: true
I am currently trying to persist the following class with the GORM MongoDB plugin for grails:
class Result {
String url
def Result(){
}
static constraints = {
}
static mapWith="mongo"
static mapping = {
collection "results"
database "crawl"
}
}
The code I'm running to persist this class is the following:
class ResultIntegrationTests {
#Before
void setUp() {
}
#After
void tearDown() {
}
#Test
void testSomething() {
Result r = new Result();
r.setUrl("http://heise.de")
r.getMetaClass().setProperty("title", "This is how it ends!")
println(r.getTitle())
r.save(flush:true)
}
}
This is the result in MongoDB:
{ "_id" : NumberLong(1), "url" : "http://heise.de", "version" : 0 }#
Now the url is properly persisted with MongoDB but the dynamic property somehow is not seen by the mapper - although the println(r.getTitle()) works perfectly fine.
I am new to groovy so I thought that someone with a little more experience could help me out with this problem. Is there a way to make this dynamically added property visible to the mapping facility? If yes how can I do that?
Thanks a lot for any advice...
Rather than adding random properties to the metaClass and hoping that Grails will both scan the metaClass looking for your random properties and then persist them, why not just add a Map to your domain class, (or a new Key/Value domain class which Result can hasMany) so you can add random extra properties to it as you want.
try this doc
#Test
void testSomething() {
Result r = new Result();
r.url = "http://heise.de"
r.['title'] = "This is how it ends!" //edit: forgot the subscript
println r.['title']
r.save(flush:true)
}
BTW, Instead of using gorm or hibernate you can always use directly java api / gmongo.
please take a look at the following snippet:
public IEnumerable<T> Query(Expression<Func<T, bool>> filter)
{
return filter != null ? this.ObjectSet.Where(filter) : null;
}
As for example:
public IQueryable<Department> Query(Expression<Func<Department, bool>> filter)
{
return _context.Departments.Where(filter);
}
(original source: http://blogs.microsoft.co.il/blogs/gilf/archive/2010/06/21/revisiting-the-repository-and-unit-of-work-patterns-with-entity-framework.aspx)
Can anyone provide some concrete examples of how to go about actually calling the second method with an actual query?
Thanks!
To say get all departments with Sales over $100
var deparments = deparmentsRepository.Query(d => d.TotalSales > 100.0m);
Func and Expression> can both be declared the same way using lambda syntax.
In fact there's an example in the article (in the last code snippet) you linked to already for this.
foreach(var department in uow.Departments.Query(d => d.Budget > 150000)) { ... }
Given that Query returns IQueryable there's no reason you can't build into more complex queries.
var deparments = deparmentsRepository.Query(d => d.TotalSales > 100.0m)
.Select(d => new { ... });
Assuming Manager and Department have a foreign key you don't need that join.
var deparments = deparmentsRepository.Query(d => d.Manager.Name.StartsWith("A"));
I'm trying EF with the EFPocoAdapter for the first time. I have a relatively simple TPH scenario with one table and two types, each inheriting from an abstract base class.
My model validates through EdmGen, and my PocoAdapter.cs and xxxEntities.cs files generate fine as well. (well, actually, there are some namespace problems that I'm currently tweaking by hand until we figure out where to go next.)
When I run a simple test to retrieve data:
using (CINFulfillmentEntities context = new CINFulfillmentEntities())
{
// use context
var alerts = from p in context.Notifications.OfType<Alert>()
select p;
foreach (var alert in alerts)
{
Assert.IsNotNull(alert);
}
}
I get an error in the PocoAdapter class, claiming that PocoEntity is null is the following method inside my base class's adapter:
public override void PopulatePocoEntity(bool enableProxies)
{
base.PopulatePocoEntity(enableProxies);
PocoEntity.Owner = _Owner.CreatePocoStructure();
if (!(PocoEntity is IEntityProxy))
{
}
}
Any ideas from anyone?
So, after a little more debugging, I think this is related to proxies. Inside PocoAdapterBase we have the following method:
protected PocoAdapterBase(TPocoClass pocoObject)
{
_context = ThreadLocalContext.Current;
bool allowProxies = false;
if (_context != null)
{
allowProxies = _context.EnableChangeTrackingUsingProxies;
}
_pocoEntity = pocoObject ?? (TPocoClass)(allowProxies ? CreatePocoEntityProxy() : CreatePocoEntity());
Init();
InitCollections(allowProxies);
RegisterAdapterInContext();
}
The line that sets _pocoEntity calls CreatePocoEntityProxy, which returns null.
More info as I find it.