w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Returning a generic list in java
I have code that looks exactly like this that is used by an ExtJS front-end, so I'm kinda making a guess that you are doing something similar. My Response object just wraps an Object. public class Response { public static Response createSuccess(Object data) { return new Response(true, SUCCESS_MSG, data); } public static Response createFailure(String msg) { return new Response(false, msg, EMPTY_LIST); } private boolean successful; private String message; private Object data; // ... } Then my web tier is written using Spring MVC which is configured to serialize the Object to a JSON string when it returns the response. But my whole server-side manipulates domain objects, rather than passing around/parsing json. @RequestMapping(method = Reques

Categories : Java

How to remove 'Type Safety'/'Unchecked conversion' warning from returning generic List in Java?
Since you put the spring tag in your question I assume that you are already using Spring. In that case using SpringData and JPA instead of Hibernate-specific stuff would be much easier. Otherwise you can't really get rid of the warning because you can't change the api.

Categories : Java

Linq to Entities - Get list of all unique related entities
If you want all the unique tag names you can do: places.SelectMany(x => x.Tags).Select(x => x.Name).Distinct() if the two instances of the same tag are the same object then you can just do places.SelectMany(x => x.Tags).Distinct(); if they are different objects then you can do places.SelectMany(x => x.Tags).GroupBy(x => x.TagId).Select(g => g.First()); UPDATE after new comment. Add ToList() to then end to convert the result into a list. places.SelectMany(x => x.Tags).Select(x => x.Name).Distinct().ToList(); places.SelectMany(x => x.Tags).Distinct().ToList(); places.SelectMany(x => x.Tags).GroupBy(x => x.TagId).Select(g => g.First()).ToList();

Categories : Asp Net Mvc

How to convert Generic List to Generic List ?
Try this List<UsageCPU> cpus = (from a in db.UsageCPUs where a.ServerID.Contains(match) group a by a.ServerID into b orderby b.Key select new UsageCPU //Added UsageCPU { ServerID = b.Key, Usage = b.FirstOrDefault().Usage }).ToList(); Update Try this once Usage = (double)b.FirstOrDefault().Usage Update as per error The entity cannot be constructed in a LINQ to Entities query List<UsageCPU> cpus = (from a in db.UsageCPUs where a.ServerID.Contains(match) group a by a.ServerID into b orderby b.Key se

Categories : C#

Method with 2 entities as Generic C#
You could shorten that quite a bit using LINQ: public static List<Entity1> Method1(List<AssociationEntity> searchlist) { return searchlist.Select(x => new Entity1() { entity.ID = x.ID, entity.NAME = x.NAME }).ToList(); }

Categories : C#

Convert generic.list to generic list product
Use this instead: var materials = list.Select(x => x.ProductMaterial).Distinct().ToList(); Or: List<string> materials = list.Select(x => x.ProductMaterial).Distinct().ToList(); The only thing that is different is the type of the materials variable.

Categories : Linq

How to order entities by key in a generic manner?
This Jon's answer was very helpful. Then I can return only strings for key properties and call OrederByProperty and ThenByProperty

Categories : Dotnet

Dynamic LINQ to Entities where EntityType is generic
var query = from c in AnyContext.AnyEntity select c; This is exactly the same as: var query = AnyContext.AnyEntity; In other words, if the context type and Entity Set property are selected by the user, you could just start with something like this: var query = (IObjectSet<T>) GetObjectSetViaReflection(context, propertyName); Also, I'm not sure what other versions of Entity Framework have this, but as of .NET 4.5, you can invoke CreateObjectSet to produce the query: IObjectSet<T> query = context.CreateObjectSet<T>(); // or, if the context has multiple properties with the same type, // you can specify a name. IObjectSet<T> query = context.CreateObjectSet<T>(propertyName);

Categories : C#

Linq to Entities using joins and generic Lists
This code is not doing anything with the joined clients data. You can see it is just selecting events: var context = from events in db.Event_Setup join clients in db.Client_Info on events.ClientId equals clients.ClientId select events; Once you get out of that LINQ statement, clients is gone. It doesn't merge any data for you. You need to do a projection, like this: var context = from events in db.Event_Setup join clients in db.Client_Info on events.ClientId equals clients.ClientId select new EventData { Event_Title = events.EventTitle, Name = clients.ClientFirstName, Start_Date = events.EventDateFrom, End_Date = events.EventDateFrom

Categories : Linq

.NET LINQ to Entities base where clause for generic Type
I think LINQ to Entities does not know how to match the cast operator to SQL request. As a suggestion, you could try something like that: IEnumerable<IPublishable> ReadPublishable(Expression<Func<DomainModelType, bool>> condition) The expression act as a predicate. So you pass to the ReadPublishable function a predicate that filters the IPublishable objects you need. I tried successfully but only on simple predicates so, I do not know whether that works if you make use of "is" or "as" operators.

Categories : C#

Method for convert generic list to another generic list
You can do it using LINQ, but you still need to provide a function that should be used to convert elements: public static List<TResult> ListCopy<TSource, TResult>(List<TSource> input, Func<TSource, TResult> convertFunction) { return input.Select(x => convertFunction(x)).ToList(); } And sample usage (with simple casting as conversion function) var t = ListConvert(l, x => (Two)x);

Categories : C#

Query for returning properties from several entities
As has already been mentioned in the comments there should be navigation properties between your classes but if you really want to flatten the data but maintain objects that can be updated elsewhere then you could do something like this: using(var _ctx = new EFEntities()) { var queryResult = from a in _ctx.a join b in _ctx.b on a.b_ID equals b.ID join c in _ctx.c on b.c_IDequals c.ID select new { a = a, b = b, c = c }; }

Categories : C#

Returning unique valued entities with their count?
This will do the trick SELECT tag, COUNT(*) `count` FROM table1 GROUP BY tag ORDER BY `count` DESC Output: | TAG | COUNT | |------|-------| | food | 2 | | shop | 1 | Here is SQLFiddle demo

Categories : Mysql

Returning child entities from a parent entity with JPA join
So you have a couple of options. You can use the following annotations: @ManyToOne @JoinColumn This is how you would use it. public class User { // your standard fields / columns in database @OneToMany (Fetch can be of eager/ lazy) @JoinColumn (name="column to join on", referencedColumnName="column to join on in parent class") private List<Pet> pets; } public Class Pet { //data fields } What essentially happens is the list of pets is populated when you are querying for the user object. Using JPA to Query the DB. So i am guessing that Your user would have some sort of id and the pet table would have some sort of Id to the user that are linked. So we would do the following Select * from user where user_id = ?; this will essentially give you the user obj

Categories : Java

LINQ to Entities returning NULL when searching by GUID
All solution that could work in a scenario like this is to create a view and do just a one liner code to access it var q = EC.OrderProductVariants.SingleOrDefault(u => u.OrderGuid.Equals(guid));

Categories : Entity Framework

CoreData in XCode create a NSFetchRequest returning all entities from today
Yes it is possible. You can specify a variable $TODAY and use it in code like so: NSFetchRequest *fetchRequest = [self.managedObjectModel fetchRequestFromTemplateWithName:@"ScanFetch" substitutionVariables:@{@"TODAY":[NSDate date]}];

Categories : Xcode

Running inline SQL with Entity Framework 5 and returning tracked Entities
Accoring to this: http://msdn.microsoft.com/en-us/data/jj592907.aspx you want the following: public IEnumerable<T> ExecuteSelect<T>(DbContext context, string table) { IEnumerable<T> entities = context.Set<T>.SqlQuery("SELECT * FROM " + table).ToList(); return entities; } myContext.Cats.Where(c => true) returns IQueriable<Cat> (not DbSet) BUT Your returned set will actually be finalized already (eg you cant add extra bits to your query later) so having it Queriable is misdirecting.

Categories : C#

Linq expression to filter an a list of entity's collection, and maintain list of entities
var r = Foos.Select(x => new Foo() { Id = x.Id, Name = x.Name, Bars = x.Bars.Where(y => y.Age <= 25 && y.Age >= 5).ToList() });

Categories : C#

How To Cast Generic List of One Type To Generic List of an Unknown Type
If you know that each item in the list is of type ObjectType, you can do this: List<object> sourceList = new List<object>() { 1, 2, 3 }; List<int> resultList = sourceList.Cast<int>().ToList(); If you actually want to convert each item in the list in a generic way, the simplest way would be to do something like this: public static IEnumerable<T> ConvertTo<T>(this IEnumerable items) { return items.Cast<object>().Select(x => (T)Convert.ChangeType(x, typeof(T))); } This would be implemented as an extension method, so you can write: List<object> sourceList = new List<object>() { 1, 2, 3 }; List<string> resultList = sourceList.ConvertTo<string>().ToList(); If the target type isn't known at compile-time, you would i

Categories : C#

Get Sum of Property from Generic list having another generic list
I think this can be improved, but this is what I had time to do: var searchTerms = searchResponseList.GroupBy(g => g.SearchTerm) .Select(x => x.Key); foreach (var searchTerm in searchTerms) { var matchingDataClasses = searchResponseList.Where(response => response.SearchTerm == searchTerm) .SelectMany(response => response.lstDataClass); // Output the data var data = matchingDataClasses.GroupBy(g => g.Date) .Select(x => new { SearchTerm = searchTerm, Date = x.Key, TotalRecords = x.Sum(dataClass => dataClass.NoOfRecord) });

Categories : Linq

returning reference of generic class
Q1 - doesn't matter. Q2 - Like constructors normally work. Nothing special. Q3 - I see no evidence of an iterator or function that returns one or uses one. Rather baffled by the question.

Categories : C++

Returning a generic container without templating the class
Possibly what you are looking for are traits classes. Andrei Alexandrescu termed them the "else-if-then of types". A traits class simply carries information (like types) and algorithms (like, say, "advance"). You first define the general information, which will apply to any type T, and then you specialize the traits class for specific types U which grant the special behavior. In your case (an example more complex than it needs to be): #include<iostream> #include<map> template<typename T> struct container_traits { using container_t = std::map<int, int>; }; class Foo { public: using key_type = typename container_traits<Foo>::container_t::key_type; using mapped_type = typename container_traits<Foo>::container_t::mapped_type; using size_type

Categories : C++

Returning a generic object on Java from abstract class
So first, I think the best answer is to make your class generic. But if you really don't want to do this you could do something like this: public <T> T getValue(Class<T> type) { return (T)input; } In some way you need to provide the expected type for the return value to the class. This can either be done my making that class generic or the method generic.

Categories : Java

Async method returning Task with generic constraint in C#
Although I am not sure this is the best solution (or feasible in your specific use case), what you can do is: public class Response { public bool Success { get; private set; } public ExceptionDispatchInfo ErrorInfo { get; private set; } public bool HasFailed { get { return !Success; } } public static T CreateErrorResponse<T>(ExceptionDispatchInfo errorInfo) where T : Response, new() { var response = new T(); response.Success = false; response.ErrorInfo = errorInfo; return response; } } Usage: catch (HttpRequestException hex) { return Response.CreateErrorResponse<T>(ExceptionDispatchInfo.Capture(hex)); // should compile (I did not check) }

Categories : C#

What method signature is appropiate returning a generic object?
I think you are looking for this signature: public <T1 extends GenericMessage> List<GenericMessage<T1>> getList(Class<T1> clazz) { return new ArrayList<T1>(); } You'll find more info about generic methods here. EDIT Based on what I understand from your sample code, I would go for something like (I corrected some syntax errors in your code): private class GenericMessageListCreator { public <U, V extends GenericMessage<U>> List<U> getList(Class<V> clazz){ return new ArrayList<U>(); } } private class GenericMessage<T> { public GenericMessage(){}; private T internalValue; public void setValue(T value) { this.internalValue = value; } public void echoValue() { Sy

Categories : Java

updating values in a Generic list by comparing with another list (different class)
In .NET 4.0 you can do this: var listA = GetGenericListA(); var listB = GetGenericListB(); var listAandB = listA.Zip(listB, (a, b) => new {a, b} ); foreach (var item in listAandB) { if (item.a.Somefield == item.b.SomeFieldb) { item.a.firstData = item.b.someData; item.a.secondData = item.b.someotherField; } } It might be not the fastest way, but it is quite fast and it is easy to read / maintain.

Categories : C#

Saving a list of entities to the db - MVC
You're so close! // create a new list of your entity Location (may not be in namespace Data) var locationList = new List<Data.Location>(); foreach (var loc in model.LocationList) { var location = new Data.Location { PersonId = model.PersonId, SiteCode = loc.SiteCode, IncidentId = loc.IncidentId }; locationList.Add(location); } using (var db = new MyEntities()) { db.Order.AddObject(incident); foreach (var item in LocationList) { db.Location.AddObject(location); } db.Comment.AddObject(comment); db.SaveChanges(); } OR: since you already have the LocationList on your model, use that instead using (var db = new MyEntities()) { db.Order.AddObject(incident); foreach (var loc in model.LocationList) {

Categories : C#

JPA / Get list of entities as references
You could also do something like select idField from YourEntity where .. and similarly in your criteria query, just use the YourEntity.idField_ value.

Categories : Java

Best way to return list of entities in many-to-many situation
You should use Select return _db.UserGroupUsers.Where(x => x.UserId == Id) .Select(t => t.UserGroup) .ToList();

Categories : C#

Pivot List of entities using LINQ in C#
Maybe this will reduce few loops. List<Entity> pivotedEntities = new List<Entity>(); int index = 0; foreach (Entity entity in results) { index = pivotedEntities.IndexOf(e => e.Id == entity.Id); if (index>-1) { pivotedEntities[index].RelatedEntities.Add(entity.RelatedEntity); } else { pivotedEntities.Add(new Entity()); } } return pivotedEntities.AsQueryable();

Categories : C#

Iterating over list of list elements and returning error message if integer has certain value
Use the any() function with a generator expression testing each nested list: if any(bread[2] > 80 for bread in breadsticks): print("You have entered too many breadcrumbs") This will only test as many nested lists as needed to find any for which the test is True. Note that it is simpler to just loop directly over breadsticks in loops: for bread in breadsticks: print(bread[2])

Categories : Python

find GAE datastore entities by CompositeFilterOperator in a key list subset
You can combine key and property filters. If I understand your data above, the query would be: Query q = new Query("Product"); // favourite product key filter (max 30 in listOfProductIDs because this is IN query) query.addFilter(Entity.KEY_RESERVED_PROPERTY, Query.FilterOperator.IN, listOfProductIDs); // add the property filters query.addFilter("color", Query.FilterOperator.EQUAL, "blue"); query.addFilter("tag", Query.FilterOperator.EQUAL, "sport");

Categories : Google App Engine

How to delete an entity from a template with a list of entities (CRUD)?
if you only want to have as much delete buttons as items in your index here's how to easily do it. In the indexAction, add the following loop and don't forget to pass the parameter to the view. public function indexAction() { $em = $this->getDoctrine()->getManager(); $entities = $em->getRepository('FooBundle:Link')->findAll(); $deleteForms = array(); foreach ($entities as $entity) { $deleteForms[$entity->getId()] = $this->createDeleteForm($entity->getId())->createView(); } return array( 'entities' => $entities, 'deleteForms' => $deleteForms, ); } Basicaly I just loop over all my entities and create the corresponding delete form using the built-in method generated by the crud, storing each form in an a

Categories : Forms

JPA Criteria API persistent field IN expression using list of entities
You can try this, Criteria criteria = getSession().createCriteria(Task .class); criteria.createAlias("owner.id", "filterUsers"); criteria.add(Restrictions.in("filterUsers", <List that contains user ids>));

Categories : Java

How to query all child objects of a list for matching entities?
Use SelectMany (MSDN) foreach(Bar p in fooList.SelectMany(a => a.Bars.Where(b => b.BarID == barID))) { if (p.Bazes == null) { p.Bazes = new List<Baz>(); } p.Bazes.Add(bazID); } Update as a.Bars could potentially be null; foreach(Bar p in fooList.Where(a => a.Bars !=null).SelectMany(a => a.Bars.Where(b => b.BarID == barID))) { if (p.Bazes == null) { p.Bazes = new List<Baz>(); } p.Bazes.Add(bazID); }

Categories : C#

Generic Type x Generic Parameter: Building a "very generic" structure
Well, first of all, you're overcomplicating this. All you really need to do is: public void add(final Tree<? extends T> subTree) { Theres no need to parameterize add(). But anyways, I'll address your original attempt: You want SubTree extends Tree<Leaf>, because even if Leaf extends T you can't guarantee that SubTree extends Tree<T> with SubTree<Leaf> matches. E.g. if your class hierarchy is: public class Base { } public class A extends Base { } public class B extends Base { } If Leaf is A and SubTree is Tree<B> then add (final SubTree<Leaf>) does not match Tree<B>. So conceptually you actually want this: public <Leaf extends T, SubTree extends Tree<Leaf>> void add(final SubTree<Leaf> subTree) { Of course that is not va

Categories : Java

How one to many relationship gets persisted in JPA if i have thousands of related entities already in data base and i add new entities in collection
If you want to add new instances to a relation between two already existent entities (a one to many in this case) then you must first fetch from the database the entity that contains the collection; in your case myEntity. So, when you load that entity you are bringing it to memory. If you had defined the relation between those two as EAGER then all the related entities (the ones in the collection) will be fetched as well at the same time than the parent one. If you, otherwise, had defined the relation as LAZY then the related entities will be loaded when you access the collection (in other, words, when you invoke the getter getXXX method for that collection). This happens that way because JPA implementations (now I'm thinking on Hibernate) return proxies of the entities instead of actual

Categories : Java

Minecraft Bukkit - How can I use item entities and falling block entities as projectiles?
You could replace a bow's arrow projectile with your own custom projectile, such as an item entity. You would catch the ProjectileLaunchEvent and do something like this: Entity arrow = event.getEntity(); Vector velocity = arrow.getVelocity(); Item item = arrow.getWorld().dropItem(arrow.getLocation(), ItemStack); item.setVelocity(velocity); If you wanted to deal damage, you would have to constantly track it's location with schedulers, check if it intersects a player, and deal the appropriate amount of damage. Or, if you want a simpler approach, just see if a player picks up the item, take the item out of their hands, and deal damage.

Categories : Java

linq to entities if filter parameter is null then select all entities?
Normally you do it this way: IQueryable<Brief> briefs = NeptuneUnitOfWork.Briefs.Where(b => b.ID == briefID); if (competitorID != null) { competitors = briefs.Select(b => b.BriefCompetitors.Where(b=>b.ID == competitorID)); } else { competitors = briefs.Select(b => b.BriefCompetitors); } Technically you could leave the problem to the SQL Server: // Note the || clause competitors = briefs.Where(b => b.ID == briefID) .Select(b => b.BriefCompetitors.Where(b=>b.ID == competitorID || competitorID == null));

Categories : Linq

Getting a singleton instance using SimpleInjector for a class which implements a generic type, not actually returning a singleton
You made the following registration: _container.AddRegistration( serviceType: typeof(ICacheManager<SettingsData>), registration: registration); And you're doing the following resolve: _container.GetInstance<SettingsCache>(); You haven't registered SettingsCache explicitly, but only ICacheManager<SettingsData>. Since SettingsCache is a concrete class, Simple Injector will resolve it as transient instance for you. The solution is to either register SettingsCache explicitly or resolve ICacheManager<SettingsData> instead. You can make a second registration with using the same Registration instance. For instance: _container.AddRegistration( serviceType: typeof(SettingsCache), registration: registration); The Diagnostic Services will warn you abo

Categories : C#



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.