w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Can List.Distinct() apply to the list type of List>?
That's because List<T> has no Equals and GetHashCode implemented, so standard reference comparison is being performed. And it returns false, because you have two separated lists. You can write your own IEqualityComparer<List<string>> implementation and provide it as Distinct method parameter. Within the comparer you can use Enumerable.SequenceEqual) method to check if lists has the same content.

Categories : C#

How should i create datacontract for a List of class which contain nested list of classes as properties
What you have in your example is fine and will automatically serialize correctly. I recommend attributing your classes with [DataContract] and your properties with [DataMember] for explicitness.

Categories : Wcf

How to get a list of keys from a collection of list of properties with key value pairs
If your list is a collection of KeyValue pairs then can you not just iterate this collection and build up a new list of strings representing the Key Dim l2 As New List(Of String) For Each kvp As KeyValuePair(Of String, String) In res(0) l2.Add(kvp.Key) Next

Categories : Asp Net

A copy of a list is altered on operations on the original list
You are only storing references to the original list. You want to create copies instead: bak.append(x[:]) or bak.append(list(x)) The [:] syntax creates a new list from a slice from the first to the last element of the original list.

Categories : Python

Class with multiple List Properties of same type but with different restrictions
You are talking about EntityFramework (Linq to entities) right? If so, Include() is a Method of Linq To Entities to include a sub-relation in the result set. I think you should place the Where() outside of the Inlcude(). On this topic you'll find some examples on how to use the Include() method. So I suggest to add the Include()'s first to include the relations "Members" and "Leaders" and then apply your Where-Statement (can be done with one Where()). return db.Teams .Include("Team.Members") .Include("Team.Leaders") .Where(t => string.IsNullOrWhitespace(t.Members.Experience) ... ) What is unclear to me is your where criteria and your use-case at all as you are talking of getting a list of Teams with Leaders and Members. May above example will return a list of Teams that

Categories : C#

property of type list modifying the original set of values in the list even when it's readonly
The readonly keyword means the variable is read-only -- but it doesn't guarantee that the object itself is immutable. For illustration: class Numbers { readonly List<int> num; public Numbers() { // ok - can write to read-only variables in the owner's constructor num = new List<int> { 1, 2, 3, 4 }; } void Test() { // this is fine -- I'm not writing to "num", just changing its state num.Clear(); // compiler error: "a readonly field cannot be assigned to" num = new List<int>(); } } If you want a read-only collection, there are .Net types that serve that purpose; see for example ReadOnlyCollection<T>. Related: Eric Lippert's famous article on different kinds of immutability.

Categories : C#

Cannot implicitly convert type '.List' to '.List'
You are selecting to an anonymous type, which is not a Customer. If you want to do (sort of) this, you can write it like this: return db.Customers.Select(x => new Customer { Name = x.CustName, Email = x.CustEmail, Address = x.CustAddress, ContactNo = x.ContactNo }).ToList(); This assumes the properties on your Customer object are what I called them. ** EDIT ** Per your comment, If you want to return a subset of the table, you can do one of two things: Return the translated form of Customer as I specified above, or: Create a new class for your business layer that only has only those four fields, and change your method to return a List<ShrunkenCustomer> (assuming ShunkenCustomer is the name that you choose for your new class.)

Categories : C#

create an adjacency list type structure from a list of pairs
You can do this with LINQ's GroupBy method, like this: var adj = sList .GroupBy(p => p.val1) .ToDictionary(g => g.Key, g => g.Select(p => p.val2).ToList()); Note that this would not compute a transitive closure of your graph, i.e. only the direct links will be present. In .NET 4 and up you can also use Tuple<int,int> instead of making your own Pair class.

Categories : C#

TypeError: unsupported operand type(s) for -=: 'list' and 'list'
lista -= [i] translates to lista = lista - [i]. You can't subtract from a list (you can add however—and do—which concatenates the two iterables together). If you want to remove an element, you can lista.pop() it off or slice it: lista = lista[:-1].

Categories : Python

Type inherited from List cannot be assigned with List
You cannot do this. Consider: public class MyList : List<string> { public string DoSomething() { return "Something"; } } //... List<string> l = new List<string>(); ((MyList)l).DoSomething(); // ERROR - List<string> does not define DoSomething()!

Categories : C#

Python: given a list of lists, create a list ordered by the number of occurrences in inner list
You can use collections.Counter to keep a counter for each element inside each sublist. Something like this, >>> from collections import Counter >>> lst = [['a','b','c'], ['a'], ['a','b']] >>> counts = Counter() >>> for sublst in lst: ... for ele in sublst: ... counts[ele] += 1 ... >>> [ele for ele, _ in counts.most_common()] ['a', 'b', 'c']

Categories : Python

iterating list of array-list and assigning each list to single dynamically created div in jsp
Try this, <c:forEach var="user" items="${userList}" varStatus="count"> <div id="col${count}"> <c:out value="${user.name}"/> </div> </c:forEach>

Categories : Java

In a responsive site design, how do i put a list below other list that contains a sub-list without overlap the main lists
Pretty simple : remove the fixed height of your li.menulinks, add a "header" (green rounded rectangle with 35px height) div as first child of the li and...you're set ! Look at this fiddle : http://jsfiddle.net/32pga/ <div class="sitemap"> <div class="row-fluid"> <ul> <li class="menulinks"> <div class="menulinks-header"></div> <ul> <li class="submenulinks"> <div>Test 1</div> </li> <li class="submenulinks"> <div>Test 2</div> </li> <li class="submenulinks"> <div>Test

Categories : HTML

How to modify the style in list(ordered list and unordered list) in HTML?
Here you go. WORKING DEMO The HTML: <ul style="list-style-type:decimal;"> <li>First</li> <li>Second</li> <li>Third</li> </ul> The CSS: li{ position: relative; } li:before{ position: absolute; left: -13px; content: ')'; background:white;} Hope this helps.

Categories : HTML

Why does Haskell let me return an empty list where a list inside a list is expected?
Because [] is of type [[a]] in this case: it is a list containing exactly 0 alpha lists. In general, the empty list can match any list type because every element (all zero of them) is of the correct type.

Categories : Haskell

How to add List containing item of type List ,int,string into another List
Use the power of LINQ: var B = A.GroupBy(x => new { x.Name, x.EngineType }) .Select(g => new Car { Name = g.Key.Name, EngineType = g.Key.EngineType, Months = g.SelectMany(x => x.Months.Select((y,i) => new { i, y = int.Parse(y) })) .GroupBy(x => x.i) .OrderBy(g2 => g2.Key) .Select(g2 => g2.Sum(x => x.y).ToString()).ToList() }).ToList();

Categories : C#

Excluding one list of items from another
You can read ID values into an array for processing in the below way : require 'yaml' yml = <<-_end_ --- Level1: Seattle: Name: "Rick" ID: "95155" Time: "2:00 PM" Car: "Hyundai" Denver: Name: "Arnold" ID: "82594" Time: "2:00 PM" Car: "Mitsubishi" Level 2: San Antonio: Name: "James" ID: "96231" Time: "2:00 PM" Car: "Honda" Minneapolis: Name: "Ron" ID: "73122" Time: "2:00 PM" Car: "Dodge" _end_ hsh = YAML.load(yml) # => {"Level1"=> # {"Seattle"=> # {"Name"=>"Rick", "ID"=>"95155", "Time"=>"2:00 PM", "Car"=>"Hyundai"}, # "Denver"=> # {"Name"=>"Arnold", # "ID"=>"82594", # "Time"=>"2:00 PM", # "Car"=>"Mitsubishi"}}, # "Level 2"=> # {"San Antonio"=> #

Categories : Ruby

Unmarshall xml list of objects to java list without class list
You could use JAXB with StAX to do the following: import java.util.*; import javax.xml.bind.*; import javax.xml.stream.*; import javax.xml.transform.stream.StreamSource; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(User.class); XMLInputFactory xif = XMLInputFactory.newFactory(); StreamSource xml = new StreamSource("src/forum17047306/input.xml"); XMLStreamReader xsr = xif.createXMLStreamReader(xml); List<User> users = new ArrayList<User>(); Unmarshaller unmarshaller = jc.createUnmarshaller(); while(xsr.getEventType() != XMLStreamReader.END_DOCUMENT) { if(xsr.isStartElement() && "User".equals(xsr.getLocalName())) {

Categories : Java

Getting a list of values from a list of dict in python: Without using list comprehension
You could use map() here. map() applies the lambda to every item of testList and returns it as a list. >>> testList = [{'id': 1L, 'name': u'Library'}, {'id': 2L, 'name': u'Arts'}, {'id': 3L, 'name': u'Sports'}] >>> map(lambda x: x['name'], testList) [u'Library', u'Arts', u'Sports']

Categories : Python

In python, what happens, will the length of a list decrease if I add part of the list to another list?
The string "hi" will be split into chars and assigned to example when you do example+=python[0] So example in this case will contain ['h','i']. Also, the list python will not lose an element.

Categories : Python

How to assign List or List to List
I don't think there's an easy way to do that using only strongly typed collections1, since there is no covariant collection interface that exposes a Remove method... I see 2 possible solutions: use the non-generic ICollection interface, that is implemented by List<T>: var collection = (ICollection) CouldBeBearsOrGoats; collection.Remove(whatever); The drawback is that a collection that implements ICollection<T> might not implement ICollection... use dynamic: dynamic collection = CouldBeBearsOrGoats collection.Remove(whatever); But it's probably slower than the previous approach. 1 assuming you don't want to change the actual type of the collections by casting items to IAnimal

Categories : C#

Create larger list from an existing list using a list comprehension or map()
How about: >>> atom_indices = [0, 4, 5, 8] >>> coords = [3*a+k for a in atom_indices for k in range(3)] >>> coords [0, 1, 2, 12, 13, 14, 15, 16, 17, 24, 25, 26] We can nest loops in list comprehensions in the same order we'd write the loops, i.e. this is basically coords = [] for a in atom_indices: for k in range(3): coords.append(3*a+k) Don't be afraid of for loops, though, if they're clearer in the situation. For reasons I've never fully understood, some people feel like they're being more clever when they write code horizontally instead of vertically, even though it makes it harder to debug.

Categories : Python

when appending a list with math using another list, how do i make the second list the same length as the first ?
You need to iterate over each elements in start_list: for item in start_list: # for each element in `start_list` square_list.append(item ** 2) # add square of `item` in `square_list` square_list.sort(); # finally sort the list or you can use sorted() function over generator expression: >>> sorted(item ** 2 for item in start_list)

Categories : Python

Appending to create a list instead of creating a list inside a list
Use extend: for item in items: forename = re.findall(pattern2, item) surname = re.findall(pattern3, item) mainlist.extend(surname) myList.extend(L) adds the individual elements of L onto myList. It's similar to: for element in L: myList.append(element)

Categories : Python

Why does adding a list to another list, using add range, remove the elements from the first list?
It's because of the IEnumerable. When you set groupsToAdd to the result of groups1.Where(g => false == groups2.Contains(g)) there is deferred execution, which means that the query is not run until AddRange() and then again at Dump(). Because the list, groups2, now contains the elements they no longer are a result of the original query.

Categories : C#

create a list from another list and remove elements from copied list
Yes your understanding is correct. List newList = new ArrayList(collection); will do a shallow copy. You can modify the newList without affecting the original collection, but they will each reference the same elements so if you modify an element in one list, the other list's element will also get the change. This is called a Shallow Copy. Here's a visual representation of what I've described: The things at the bottom are the objects in your array.

Categories : Java

What kind of List is List list = Database.getAllData();?
You don't have to know; that's the point. The interface is what matters to you, not the implementation. You can't know without looking at the source of that method. But even if you do, it's immaterial to your client. All you call are List methods.

Categories : Java

A message body reader for Java class java.util.List, and Java type java.util.List<>, and MIME media type text/html was not found
I deleted all generated classes and all restful classes and the GroupUClient then the program works without problems. change from public ChatuserClient() { com.sun.jersey.api.client.config.ClientConfig config = new com.sun.jersey.api.client.config.DefaultClientConfig(); client = Client.create(config); webResource = client.resource(BASE_URI).path("entities.chatuser"); } to public ChatuserClient() { com.sun.jersey.api.client.config.ClientConfig config = new com.sun.jersey.api.client.config.DefaultClientConfig(); client = Client.create(config); webResource = client.resource(BASE_URI).path("entities.service.chatuser"); }

Categories : Java

NSFileManager list directory contents excluding directories
You can go a little deeper with a directory enumerator. How about this? NSDirectoryEnumerator *dirEnumerator = [localFileManager enumeratorAtURL:directoryToScan includingPropertiesForKeys:[NSArray arrayWithObjects:NSURLNameKey, NSURLIsDirectoryKey,nil] options:NSDirectoryEnumerationSkipsSubdirectoryDescendants errorHandler:nil]; NSMutableArray *theArray=[NSMutableArray array]; for (NSURL *theURL in dirEnumerator) { // Retrieve the file name. From NSURLNameKey, cached during the enumeration. NSString *fileName; [theURL getResourceValue:&fileName forKey:NSURLNameKey error:NULL]; // Retrieve whether a directory. From NSURLIsDirectoryKey, also // cached during the enumeration. NSNumber *isDirectory; [theURL getResourceValue:&isDirectory forKey:NSURL

Categories : Objective C

List within a List - How to put new line with LinQ after List within List is over?
Console.Write( String.Join(Environment.NewLine, f.Select(flight => { var segments = flight.Segments.Where(x => x.DepartureDate > DateTime.Now); return String.Join(" ", segments.Select(segment => { return String.Format("Departure: {0}, Arrival: {1};", segment.DepartureDate, segment.ArrivalDate)); }); }); ); I personally prefer to have a Joined extension method on IEnumerable<T> which wraps String.Join (taking a delimiter and an optional transformation delegate), and a Formatted extension method on String which wraps String.Format: var output = f.Joined(Environment.NewLine, flight => flight.Segments .Where(s => s.DepartureDate > DateTime.Now) .Joined(" ", s => "Departure:

Categories : C#

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#

TSQL - Faster to use IN (list) or use NOT IN (list) for a small list?
NOT IN ('val4') is basically equivalent to WHERE NOT (column = 'val4') /* or column <> 'val4' */ whereas IN ('val1', 'val2', 'val3') is basically equivalent to WHERE ( column = 'val1' OR column = 'val2' OR column = 'val3' ) I would hope that the first option is faster, if only negligibly. The SQL engine might optimize IN differently depending on how many values you specify in the IN function and what indexes are available on your table. What behavior are you seeing that you're questioning the method to use?

Categories : SQL

How to get the list elements using list inside another list in java
You can try this ,Let say you have variables like double dtime; Timestamp tp; And listofresults is coming from query results. listofresults = results.getResultList(); If list is coming from query then put it in the loop this way in the condition of for loop for(int i=0;i< listofresults.size() ;i=i+2) { dtime=(double) listofresults.get(i); //cast because the value is of object type tp=(TimeStamp) listofresults.get(i+1); //cast because the value is of object type //do something with these variables }

Categories : Java

Using a list as "list of indexes" to address elements of another list
You could use reduce(operator.getitem, index, mylist) Here is a complete example: import operator mylist = [[1,2,3],[4,5,6],[7,8,9]] index = [1,2] val = reduce(operator.getitem, index, mylist) print(val) For NumPy arrays, there is a simpler method: import numpy as np ... myarr = np.array(mylist) val = myarr[tuple(index)] print(val)

Categories : Python

How to find out the type of list items and then create a list of that type of items?
You can do this using Reflection, for example: var listType = typeof(List<>); listType.MakeGenericType(typeof(MyType)) return Activator.CreateInstance(listType); Another example, if all you have is an instance of "MyType" but don't know what it is until runtime: public IEnumerable GetGenericListFor(object myObject){ var listType = typeof(List<>); listType.MakeGenericType(myObject.GetType()) return Activator.CreateInstance(listType); }

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#

How to show inner content in list item outside of that list item without being covered up by descending list items
You must set the z-index of the clicked 'li' higher and in return the former clicked 'li' back. Here is the example: fiddle And here the script: var oldli; $('li').click( function(){ $(oldli).toggleClass('displayNone displayBlock'); $(oldli).css("z-index","1"); $(this).toggleClass('displayBlock displayNone'); $(this).css("z-index","5"); oldli=$(this); } );

Categories : Javascript

adding a list of one type to a list of another type
Unless there is an Inheritance relationship between A and X.Y.Z you cannot have them in the same container because they are not of the same type You can use the generic superclass Object as the type of the List and this will work.

Categories : Java

Doubly-linked List copy constructor (can't copy tail-to-head)
By having a const argument, you're calling a non-const member function on const object. Non-const functions do not promise to not modify the object. You can declare these member functions as const to avoid this error: Node *getHead() const .. and so on As for your first question, I don't know how to solve it (yet), I have a few recommendations: Use nullptr instead of NULL or 0 Use list initialisation for your strings: string f { curr->getData()->getFirst() }; I suggest you debug your code line by line, using a good debugger tool, like Visual Studio; it will help you solve your problem in minutes. If you are still unsure, you can cut the amount of code to be tested, down to a few lines and post it.

Categories : C++

Write list of list to file and then retrieve it from the file as a list of list
>>> import pickle >>> banana, beans = ['Banana' , .54 , 'No' , 'Food'], ['Beans' , 1.39, 'Yes', 'Food'] >>> food = [banana, beans] >>> with open('data', 'wb') as f: pickle.dump(food, f) >>> with open('data', 'rb') as f: print pickle.load(f) [['Banana', 0.54, 'No', 'Food'], ['Beans', 1.39, 'Yes', 'Food']]

Categories : Python



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