w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Create a lambda expression from a List of objects
You need DynamicLinQ. See this blog.

Categories : C#

C# How do i return iGrouping to a list using lambda expression
It seems to me that you don't need to group at all - you just need to filter. Unless you really have more than one hint per question (with the same task and activity), you just need: public IList<Model.questionhint> GetRecordsPlease(int listTask, int listActivity) { return context.questionhints .Where(a => a.TaskID == listTask && a.ActivityID == listActivity) .ToList(); } Note that unlike your current code, this will perform the filtering in the database, rather than pulling the whole table to the client and then grouping/filtering. You need to be aware that any time you use context.SomeTable.ToList(), that will pull the entire contents of that table. I'd also strongly suggest that you change your model to use type names which fo

Categories : C#

How to set multiple values in a list using lambda expression?
Well personally I wouldn't write the code that way anyway - but you can just use a statement lambda: A statement lambda resembles an expression lambda except that the statement(s) is enclosed in braces The body of a statement lambda can consist of any number of statements; however, in practice there are typically no more than two or three. So the ForEach call would look like this: .ForEach(x => { x.BtnColor = Color.Red.ToString(); x.OtherColor = Color.Blue.ToString(); }); I would write a foreach loop instead though: var itemsToChange = objFreecusatomization.AllCustomizationButtonList .Where(p => p.CategoryID == btnObj.CategoryID && p.IsSelected && p.ID == btnObj.ID); foreach (var item in itemsToChange) {

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#

lambda list to combine string
Use String.Join string names = String.Join(",", _myList.Select(x => x.Name)); Or you can even avoid loading other columns from DB: string names = String.Join(",", DBContext.myTables.Select(x => x.Name));

Categories : C#

C# Linq or Lambda to get Dictionary> from a class
Instead of x.ToList you have to select the string property of the anonymous type first: Dictionary<string, List<string>> procTasks = baseSettings .GroupBy(x => x.ProcessStr) .ToDictionary(g => g.Key, g => g.Select(x => x.TaskStr).ToList());

Categories : C#

Select Random Unique String From List in PHP
You can use array_unique in PHP. for example if you generate an array as follows. $array = array('blue','blue','green','yellow','purple'); $out = array_unique($array); //will product //array('blue', 'green', 'yellow', 'purple');

Categories : PHP

List - Need suggestion as how to pull record from String[]
You should use File.ReadLines instead which streams the lines instead of loading all into memory first. Also, you are creating two in-memory collections here: string[] records = File.ReadAllLines(path); List<string> listOfStr = new List<string>(records); This is much more efficient in terms of memory consumption: var matchingLines = File.ReadLines(path) .Select(l => new{ Parts = l.Split(), Line = l }) .Where(x => x.Parts.ElementAtOrDefault(9) == yourSearch) .Select(x => x.Line); foreach (string line in matchingLines) Console.WriteLine(line); You haven't mentioned what delimiter separates each column, i have used white-spaces, l.Split(',') would split by comma. Enumerable.ElementAtOrDefault(9) retuns the 10th column if available, otherwise null i

Categories : C#

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#

generating unique ordered non duplicate combinations in java for a list of list
1: Is this homework? 2: How many lists do you anticipate using as a maximum? Basically... there's not going to be some sort of magical way to do this... you're going to have to check to see if the string you're building already contains the letter you're considering adding, and that's what you want to optimize -- checking if your String already contains a letter. If you're doing this for homework, I think you can use a String.contains( 'a' ) || String.contains( 'A' ) to see if the String already contains a certain letter ('a' in this case). I'll leave the rest of it to you. Note that this is an O(n^2) operation. If you're doing this for a more... industrial... application, then I see another option. If you're going to have a large number of String lists, then you'll probably want to

Categories : Java

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

Generate unique list item id for all list items in site collection
There is no comparable feature to the documentID service for Items in general out of the box. You would have to build it using Custom code. You can create a custom ID which appends the list GUID and the OOTB item ID which is unique to every item in the site collection.

Categories : Sharepoint

Using Java's built-in Set classes to count EACH(keyword) unique element in List values from a list
You are looking for Map<String, Integer> data structure, not Set Something like for(iterating over something){ Integer count =map.get(value); if( count == null){ map.put(value, 1); } else{ count++; map.put(value, count); } } Map is the data structure that maps unique to value

Categories : Java

Sorted/unique list of object instances from a larger list?
One way to do this is using itertools.groupby(): import itertools x3 = [next(g) for k, g in itertools.groupby(x2, lambda x:(x.a, x.b))] This picks the first element of each group with the same key.

Categories : Python

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

LinqPad Error: Lambda expression cannot be converted to 'String' because 'String' is not a delegate type
The problem appears to be that one or more of the properties of object "p" is not a string. However, you most likely are misunderstanding what .Include does. It eager-loads whichever related tables you specify. So if you had: Dim projects = From p In db.Projects.Include("Managers") it would eager-load all of the related records from your "Managers" table for each row in your "Projects" table when the query is executed. Somehow, I don't think this is what you are trying to accomplish with the code you posted.

Categories : Vb.Net

PHP: Random list of 52, so when repeated it's unique from the previous list?
Well there are is a small problem with the assumptions you have Rule 1 The overall goal is that each list has no relationship or common pattern to it's previous list. Rule 2 The rule is that the first element of the list and the last element can't be the start and end elements from the previous list. Those two contradict each other. First there may be no relationship, so random. So as you said shuffle (did not look at is I take your word). But the second one needs to know about the previous one. What contradicts with your previous rule. But what you could do is have the first and last element of the previous draw (the previous 52). Then you shuffle the current draw. If the first and/or last element are the same, draw again until no match is found. Also I think the word for this is

Categories : PHP

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#

C# Turning magic string into lambda expression
I wrote my own predicate builder type thing a while back. I attempted to adapt the code for posting here. This returns an expression to access a property, and can be used to build up more complicated expressions - just make sure that all the components of the expression use the exact same param object instance. This won't work as a drop in for your code. It'll will require some slight adaptations to make it work for your use I think. This outputs param => (param.Child.IntProperty == 42). You could use the predicate variable in a where clause. Let's say you had a List<Parent> called parents, you could call parents.Where(predicate). public class Parent { public string StringProperty { get; set; } public Child Child { get; set; } } public class Child { public int In

Categories : C#

Get unique list of ids from object list
You can add the id's as keys to a dictionary and obtain back the keys of it: d = {} for item in items: d[item.id] = item print d.keys() Now, d.values() contains the items which have the unified ids. As long as no two different items have the same id the above is lossless. Contrasting with other solutions (at the time of writing) this also provides a good mapping between the id and the item with the specified id.

Categories : Python

Ruby Lambda expression in Sonar Widget to find a property whose key contains a String
As far as I can see, Sonar is a Rails app, and Property is a ActiveRecord::Base subclass, the following should do what you want: properties = Property.find(:all, :conditions => ['prop_key LIKE ?','sonar.score.TitleCup:%']) Basically, instead of using the simple {:key => value}, you provide a SQL WHERE condition directly (using a placeholder). You can read about Rails query interface, and specially about conditions at Active Record Query Interface

Categories : Ruby

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#

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#

Pass lambda expression to lambda argument c++11
Try using std::function: #include <functional> int main() { int x=0; int y=0; auto f = [x,y](std::function<double(int)> func) -> double {func(0); return 0.0;}; f([x](int i) -> double {return 0.0;}); }

Categories : C++

How to search from a list inside a dictionary>
Wouldn't this be done with a linq statement? Sure. It won't be efficient, but it's pretty simple: var input = "456"; var matchingKeys = dictionary.Where(kvp => kvp.Value.Contains(input)) .Select(kvp => kvp.Key); If you want it to be efficient as well, you should store the reverse mapping too, and update both together.

Categories : C#

How do I interate through a paired list when using map and lambda?
Is this what you want? x and y are arrays of int, not float. Not that I like the double for loops, they should be replaced with a more vectorized algorithm, but to keep the change minimal and high light the problematic line, here is it: >>> a2 array([[ 0.92607265, 1.26155686, 0.31516174, 0.91750943, 0.30713193], [ 1.0601752 , 1.10404664, 0.67766044, 0.36434503, 0.64966887], [ 1.29878971, 0.66417322, 0.48084284, 1.0956822 , 0.27142741], [ 0.27654032, 0.29566566, 0.33565457, 0.29749312, 0.34113315], [ 0.33608323, 0.25230828, 0.41507646, 0.37872512, 0.60471438]]) >>> numpy.where(detect_peaks(a2)) (array([0, 2]), array([1, 0])) >>> def func1(locations): #You don't need to unpack the numpy.where result. for test_x

Categories : Python

Difference between lambda expression and expression lambda
Yes there is - or I should probably say that one defines the other. A lambda expression allows you to assign simple anonymous functions. An expression lambda is a type of lambda that has an expression to the right of the lambda operator. The other type of lambda expression is a statement lambda because it contains a statement block {...} to the right side of the expression. Expression lambda takes the form: number => (number % 2 == 0) Statement lambda takes the form: number => { return number > 5 }

Categories : C#

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

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

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

Python: Removal from a list of lambda closures
Could you structure it like so: delenda = [] for l in my_lambdas: if not l(): delenda.append(l) for item in in delenda: my_lambdas.remove(item) And just use the truthiness of the return value to remove the items at execution time? Alternatively, could you pass callable class instances that knew how to delete themselves from a registry? from functools import partial class Deleteme (object): REGISTRY = [] def __init__(self, func, *args): self.callable = partial(func, *args) def register(self): if not self in self.REGISTRY: self.REGISTRY.append(self) def __call__(self): retval = self.callable() if not retval and self in self.REGISTRY: self.REGISTRY.remove(self) return retval @classmethod def run_lambdas

Categories : Python

query list with linq lambda expressions
participants = participants .Where(p => counties.Any(c=> c.CountyId == p.CountyOfParticipationId) ) Or participants.Where(p => p.County.CollaborationId == collaborationId) should also work if you have set up relations properly

Categories : C#

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#

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#

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

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

List passed in ViewBag gets spoiled with "System.Collections.Generic.List`1[System.String]"
Your problem is due to the fact that you're trying to pass a List of strings but have assigned it to a string property in the ActionLink(). You'll need to create a small helper to explode this List out to a single formatted string of your choice. This will then be passed to the url as a (for example) comma separated string. You'd then do some magic in the controller action to rehydrate this as required back to the List.

Categories : C#

Linq and lambda function in List of custom objects
I don't entirely understand your question but I think you're looking for something like; j = series2X.TakeWhile(p => p.X < series1[0].X && p.Y < series1[0].Y).Count();' In LINQ to Objects you access properties like you would anywhere else in C#, with dot notation. p is the current item in series2 which is of type DataPoint and so is every item in series1 so you can just do p.MyProperty for any property on any type.

Categories : C#

Show list of all Enums of type except the one passed via lambda
I don't think you have the model object, as-is. You could add it as another parameter: @Html.RadioButtonForEnum(Model, model => model.Status) public static MvcHtmlString RadioButtonForEnum<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, TModel model, Expression<Func<TModel, TProperty>> expression) { string currentStatusName = expression.Compile()(model).ToString(); ...

Categories : C#



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