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#

Two-Dimensional List of Different Types
First approach: Inheritance. But you can go about and just create a List<Object>. Object doesn't care what you throw in there. But restricting that to two classes, no, that is not possible.

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#

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#

create a drop down list from a multi dimensional array
function createDropDown($name = '', $options = array()) { $dropDown = '<select name="'.$name.'">'; foreach ($options as $option ) { $dropDown .= '<option value="'.$option["name"].'">'.$option["name"].'</option>'; } $dropDown .= '</select>'; return $dropDown; } Try something like the above replaceing "name" with the field name of what you want for the value and label

Categories : PHP

Is it possible to create a List using anonymous types on both sides (input and output) of the declaration?
You can do something like below, if it works. For each different type like Class1 and Class2 you need to implement the interface. But what you are actually looking for seems like AutoMapper public interface ILoadable<T> { void LoadFrom(T other); } public class Class1 : ILoadable<Class2> { public void LoadFrom(Class2 other) { // Do property mapping here } } public static List<T1> GetList<T1, T2>(List<T2> list2) where T1 : ILoadable<T2>, new() { List<T1> list = new List<T1>(); foreach (var item in list2) { T1 t1 = new T1(); t1.LoadFrom(item); list.Add(t1); } return list; }

Categories : C#

How to convert a nested list into a one-dimensional list in Python?
You need to recursively loop over the list and check if an item is iterable(strings are iterable too, but skip them) or not. itertools.chain will not work for [1,[2,2,2],4] because it requires all of it's items to be iterable, but 1 and 4 (integers) are not iterable. That's why it worked for the second one because it's a list of lists. >>> from collections import Iterable def flatten(lis): for item in lis: if isinstance(item, Iterable) and not isinstance(item, basestring): for x in flatten(item): yield x else: yield item >>> lis = [1,[2,2,2],4] >>> list(flatten(lis)) [1, 2, 2, 2, 4] >>> list(flatten([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) [1, 2, 3, 4, 5, 6, 7, 8, 9] Works for any

Categories : Python

Can we Convert Anonymous Type to List using Linq to entity in C#?
Just use the actual concrete type instead of an anonymous one: select new Material { ID = c2.ID, MaterialParentID = c2.MaterialParentID, Name = c2.Name, ParentName = c1.Name }

Categories : C#

Linq anonymous type with list object property
You need to take the collection of desks from the data model, convert each one to a DeskViewModel, and convert the resulting sequence to a List<T>. That would look something like p.Desks.Select(d => new DeskViewModel { ... }).ToList()

Categories : C#

Java Collection: what to convert Collection> to ArrayList> or List>?
You can use the appropriate constructor: List<List<String>> yourList = new ArrayList<>(yourCollection); The order of the elements in the list is the order of the iterator of the collection.

Categories : Java

One method, multiple list types
You should make this method a generic method, in the same way that List is a generic class. You can reuse the generic parameter when giving the parameter for List: private static void MoveSuccessRecords<T>(List<T> thisList, string VUEFileName, string folderArchive, string folderError) { StreamWriter successWriter = new StreamWriter(folderArchive + VUEFileName.Replace(extension, "_COMPLETE" + extension), true); CsvWriter successCSV = new CsvWriter(successWriter); successCSV.WriteHeader<T>(); foreach (var item in thisList) { successCSV.WriteRecord(item); } successCSV.Dispose(); successWriter.Dispose(); successWriter.Close(); }

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#

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#

Storing multiple object types in a List
You could use java generic.First create a java collection (ex: List) with supper class type, Product. Now you could add any sub classes (Monitor , Keyboard etc) in your collection (List) that extends of class Product. public class Product{ } public class Monitor extends Product{ } public class Keyboard extends Product{ } List<Product> products = new ArrayList<Product>(); products.add(new Monitor()); products.add(new Keyboard());

Categories : Java

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

GWT - How to have multiple cell types on the same level and in the same children list?
In the end, I created a custom cell that has to 2 different UIRenderers. Depending on a flag from the DTO we can decide what renderer to use. Each cell type is defined in it's on xml. public class DualFaceCell extends AbstractCell<DTO> { @UiTemplate("SimpleFaceCell.ui.xml") interface SimpleFaceRenderer extends UiRenderer { void render(SafeHtmlBuilder sb); void onBrowserEvent(SimpleFaceCell o, NativeEvent e, Element p); } @UiTemplate("ComplexFaceCell.ui.xml") interface ComplexFaceRenderer extends UiRenderer { void render(SafeHtmlBuilder sb, String name); void onBrowserEvent(ComplexFaceCell o, NativeEvent e, Element p); } private final SimpleFaceRenderer simpleRenderer = GWT.create(SimpleFaceRenderer .class); private final ComplexFaceRenderer complexRenderer = GWT

Categories : Gwt

Adding a string to a List inside of a List>
You are correct, with the error, you need to understand that the List<List<string>> will take a List<string> and NOT A String. Try something like this; List<string> listOfString = new List<string>; for (int i = 0; i <= filesToRead.Count; i++) { using (var reader = new StreamReader(filesToRead[i])) { string line; while ((line = reader.ReadLine()) != null) { listOfString.add(line); } } } Then, _toLoad.add(listOfStrings);

Categories : C#

List multiple models in class based list and detail views in django
You can add extra context variables by overriding the get_context_data() function in your class: class MultipleModelsListView(ListView): model = TaskA # Class names should use capitalized CamelCase def get_context_data(self, **kwargs): kwargs = super(MultipleModelListView, self).get_context_data(**kwargs) kwargs.update({ 'taskb_list': TaskB.objects.all(), # or with some filter applied 'taskc_list': TaskC.objects.all(), 'taskd_list': TaskD.objects.all(), }) return kwargs This will give you, additional to the default context supplied by a ListView, the context variables taskb_list, taskc_list and taskd_list to iterate over. You can iterate over these in your template like this: {% for task in object_list %} {#

Categories : Django

conditionally adding multiple items to a list of lists via python list comprehension
The line html = BeautifulSoup(urllib2.urlopen('http://domain.com').read(), 'lxml') implies you have lxml installed, so you could use an XPath using | to pull out text or attribute values: import urllib2 import lxml.html as LH html = LH.parse(urllib2.urlopen('http://domain.com')) clean_data = [[elt for elt in tr.xpath('td/a/text() | td/a/@href | td/text()')] for tr in html.xpath('//table[@id="targeted_table"]/tr')] print(clean_data) yields [['http://domain.com', 'data 01', 'data 02', 'data 03', 'data 04'], ['http://domain.com', 'data 11', 'data 12', 'data 13', 'data 14'], ['http://domain.com', 'data 01', 'data 22', 'data 23', 'data 24'], ['http://domain.com', 'data 01', 'data 32', 'data 33', 'data 34']] You could also do it with a single call to the xpath met

Categories : Python

Unknown column 'list' in 'field list' php mysql multiple selections
Its super simple: $row_huff_list is not defined when the program enter the loop for the first time, only at the end of the first loop, the $row_huff_list is assigned some value, for second time its ok already, just change do-while loop to while loop, like this: while ($row_huff_list = mysql_fetch_assoc($huff_list)) { ?> <option value="<?php echo $row_huff_list['id'] ?>"> <?php echo $row_huff_list['list'] ?> </option> <?php }

Categories : PHP

How to make List of Unique data from multiple List containing duplicate values
To not use loops, use recursive calls of functions. You can use a hash array, or an object and set its properties with your values, use "true" value for simplicity. When you override, its not a problem, it will just get re-set as true. Afterwards, you loop through the hash array or object and all its properties are unique (and all have the value true). If you have a particular language of programming, mention it as a comment, I might give you the function to do it.

Categories : Java

Appending multiple list index into a single list then using join to print them
Get the content of each file first, then join them. from itertools import izip with open('file1.txt') as f1: lines1 = f1.readlines() with open('file2.txt') as f2: lines2 = f2.readlines() with open('combinations.txt', 'w+') as f3: for i, j in izip(lines1, lines2): f3.write(i + ' ' + j.split(None, 1)[-1]))

Categories : Python

Is there a way to print out an object from a script as it would appear in the REPL? (e.g. myList: List[String] = List(Hello there, World!)
The Scala equivalent of this would be the getClass method (from Java) on java.lang.Object. For instance: scala> 1.getClass res0: Class[Int] = int scala> Nil.getClass res1: Class[_ <: scala.collection.immutable.Nil.type] = class scala.collection.immutable.Nil$ scala> "hello".getClass res2: Class[_ <: String] = class java.lang.String

Categories : Scala

Finding case sensitive string in a cell from a specific list and return a value from the list
Assuming the following: Sheet 1, column a = Sheet1!A:A Sheet 1, column b = Sheet1!B:B Sheet 2, column a = Sheet2!A:A Sheet 2, column b = Sheet2!B:B You can simply insert an INDEX MATCH into Sheet1!B1 =INDEX(Sheet2!B:B,MATCH(Sheet1!A1,Sheet2!A:A,0))

Categories : Excel

Unable to create a constant value of type 'Anonymous type'. Only primitive types or enumeration types are supported in this context
The problem is the ToList() call on details. In EF, you can only refer to an IEnumerable inside a Query if that IEnumerable is of a simple type (e. g. int). However, you CAN refer to another IQueryable. Thus, dropping the ToList() call should make this work. EDIT: similarly, you should drop the ToList() call on ctx.CompanySettings. This will have the added advantage of executing only 1 query instead of 2. If you drop the ToList() on details, EF will generate something like: SELECT ... FROM RegisteredBikes rb JOIN ( /* this is your "details" IQueryable */ SELECT Serial, EmailAddress FROM BikeDetails WHERE ... ) bd ON rb.Serial = b.Serial JOIN CompanySettings cs ON ... WHERE ... EDIT: to do this across contexts, you'll need to bring the query into memory (e. g. b

Categories : C#

Selenium adding items from a Web element list to a string array list
Please try using following sample code, change xpath/data accordingly List<WebElement> resultList = _driver.findElements(By.xpath("//img[contains(@src,'tab-close.png')]/preceding-sibling::span[@class='tab-name ng-binding']")); for (WebElement resultItem : resultList){ String tabname=resultItem.getText(); if(resultItem.getText().equalsIgnoreCase("Dashboard")){ GlobalFunctions.clickOnButtonCustomised(false, _driver, By.xpath("//span[@class='tab-name ng-binding' and contains(text(),'"+tabname+"')]/following-sibling::img[contains(@src,'tab-close.png')]"), ""); } }

Categories : Java

Python encoding: list to string having special characters and numbers in the list
If you can specify the strings in your list as unicode, like: [u"Círculo", 23] [u"Triángulo", 25, 19, u"dos"] then this should work: u', '.join(unicode(x) for x in list_of_ints) Assuming you are running Python 2.

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#

Getting unique values from a list of objects with a List as a property
If I understand, you want a list of all of the unique certifications among all of the employees. This would be a job for SelectMany: var uniqueCerts = empList.SelectMany(e => e.Certifications).Distinct().ToList();

Categories : C#

Using C# LINQ to concat a filtered List to List
If names is empty, what you're meant to do is this: var names = businessNames.Select(item => item.Name).ToList(); Another option is to use the List<T>'s ConvertAll method, like so: var names = buisnessNames.ConvertAll(item => item.Name); However, if it may be not empty, you'd need to use an if statement too: var names = new List<string>(); //some code if (names.Any()) names.AddRange(/*your selected method*/); else names = //your selected method;

Categories : C#

How to parse String List into List using Gson
Your getGenericClass() won't work, you need to retrieve the class of T. You can provide it : Class<T> type; public Class<T> getType() { return this.type; } or get it at runtime (unsafe, you can find many post on this subjet I think) public Class<T> getType() { return (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; } Then to build the list token you can use this code : static TypeToken<?> getGenToken(final Class<?> raw, final Class<?> gen) throws Exception { Constructor<ParameterizedTypeImpl> constr = ParameterizedTypeImpl.class.getDeclaredConstructor(Class.class, Type[].class, Type.class); constr.setAccessible(true); ParameterizedTypeImpl paramType = cons

Categories : List

passing a List that is a class generates error, List that is string does not
It's pretty obvious what's going on here, everything you need to know is in your error message. You have 2 different declarations for the Rooms class, one in your RoomViewController and the other in your TableSource and appear to be leaking them across your classes. You need to make sure you are passing the expected type into the TableSource class. To elaborate further, your TableSource constructor looks like: public TableSource(List<CupuleAdmin.TableSource.Rooms> table) { } And you are trying to pass: List<CupuleAdmin.RoomViewController.Rooms> allrooms = new List<...>(); table.Source = new TableSource(allrooms);

Categories : C#

concatenate list by user input (string) and displaying the List
You need an append list1 += [b] instead of assignment list1 = [b] And in Python in this case its better to use for in. Also raw_input would return a string, you do not need to convert it for a in range(3): b = raw_input("cmd : ") list1 += [b] Or even better to use list comprehension as there is an overhead for appending a list. list1 = [raw_input("cmd : ") for _ in range(3)]

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

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

how do I populate a List from multiple methods with Task>?
It sounds like you're just trying to convert a List<string>[] into an IEnumerable<string>, which isn't async-specific... plain LINQ will do it: var errors = results.SelectMany(x => x); That will flatten the array of lists to just a single sequence.

Categories : C#

Hot to Create multiple list data in one drop down list
[AcceptVerbs(Http.Get)] public ActionResult GetValueExample() { ViewData["MyItems"] = GetSelectList(); return View(); } [AcceptVerbs(Http.Get)] public ActionResult GetValueExample(string MyList) { //MyList contains the selected value SelectList list = GetSelectList(); //list will contain the original list of items //... } private SelectList GetSelectList() { Dictionary<string, string> list = new Dictionary<string, string>(); list.Add("Item 1", "1"); list.Add("Item 2", "2"); list.Add("Item 3", "3"); return new SelectList(list, "value", "key"); } //... <%= Html.DropDownList("MyList", ViewData["MyItems"] as SelectList) %>

Categories : Asp Net Mvc

C++ : deleting multiple elements of a list while iterating the list
In general, the way to remove elements from a list based depending on a condition is to use the std::list::remove_if member function. bool pred(const Treenode* t) { .... } currentNewLevel.remove_if(pred); The predicate can be a functor, so it can keep any state that is required to implement the removal criteria: #include <algorithm> // for std::find_if #include <list> // unary predicate functor. Returns true if an element of a reference // list satisfies "something" and the functor call argument satisfies "somethingDifferent" struct Pred { Pred(const std::list<Treenode*>& nodes) : nodes_(nodes) {} bool (const Treenode* t) const { return std::find_if(nodes_.begin(), nodes_.end(), something) != nodes_.end() && somethingDifferent(t); }

Categories : C++



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