w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
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#

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#

Convert dictionary values to list using linq
You don't need to use Linq to get the values. The Dictionary(TKey, TValue) has a property that holds the values, Dictionary(TKey, TValue).Values: var fields = objDictionary.Values.ToList();

Categories : C#

updating list values of dictionary with the values of another dictionary and printing the result as the values of first dictionary in python
Well, first off your syntax for defining literal dictionaries is incorrect. Dictionaries are surrounded by curly brackets like this: {} instead of square brackets like this: [] If you want 'Standard_Animator' and 'Extended_Animator' to be keys for lists of colors, you would want to do something like this: legenddict = {"Standard_Animator" : ["blue", 3f7fff, 00bfff, 3fffbf, "green", bfff3f, ffbf00, ff7f00, "red"], "Extended_Animator" : ["lightgray", "blue", 3f7fff, 00bfff, 3fffbf, "green", bfff3f, ffbf00, ff7f00, "red", "magenta"} colordict = {'blue':'ff00ff', 'red':'808080', 'lightgray':'d3d3d3', 'magenta':'00ff00'} So, to print the values in legenddict using the color names in colordict, you can check to see if the colors are keys in colordict, and if so, look up the

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#

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#

Filter LINQ query using items from an external list with Lambda
Assuming that by "with lambda" you mean the "query syntax", you can rewrite your query like this: var myProducts = db.Products.Where(p => productList.Contains(p.ProductID));

Categories : Linq

LINQ/Lambda update List items by spliting them into even groups
you shoud avoid LINQ with side effects. But you can attach the object in the lists like that. List<MobileAccounts> mas = new List<MobileAccounts>(); List<SubmitSm> sms = new List<SubmitSm>(); var result = mas.Select(ma => new {Sm=(sms.First(sm => sm.RoutingLabel == ma.RoutingLabel)),Ma=ma}); foreach (var r in result) { //update Properties here }

Categories : C#

Getting rid of outer foreach loop using linq or lambda and ensuring no duplicates are added to list
You can get rid of any duplicates before processing the list: List<Document> newDocuments = new List<Document>(); List<Document> distinctItems = newDocuments .Distinct(); foreach (DocumentDetail documentDetail in documentDetails) { newDocuments.AddRange(documents.FindAll(d => d.Extension.ToUpperInvariant() == documentDetail.Extension.ToUpperInvariant())); }

Categories : C#

Building a list in a dictionary (LINQ to SQL)
You should use GroupBy: var dic = db.GetTable<History>() .Select(p => new { p.Title, p.Date}) .Where(x => x.Date >= startDateFilter && x.Date <= endDateFilter) .GroupBy(x => x.Title) .ToDictionary(g => g.Key, g => g.Select(x => x.Date).ToList());

Categories : C#

Should I be using a Dictionary or List with a linq search?
The second approach is not going to work, because arrays do not override the GetHashCode and Equals in a way that would use the data stored in the array. The first approach, however, would be slow for collections with high number of cells, because of a linear search. A better approach would be to use Tuple<sbyte,sbyte> instead of an array: Dictionary<Tuple<sbyte,sbyte>, Cell> CellList; //.... Cell thisCell = CellList[Tuple.Create(thisX , thisY)];

Categories : C#

Transfor List to Nested Dictionary using linq C#
You can try this with a pair of GroupBy and a pair of calls of ToDictionary, like this: var res = list .GroupBy(v => v.ID) .ToDictionary( g => g.Key , g => g.GroupBy(v => v.START_DATE.Date) .ToDictionary(h => h.Key, h => h.Seelct(x => x.ID_OWNER).Distinct().Count()) ); If you would like to also add the total time per day, you can do this: var res = list .GroupBy(v => v.ID) .ToDictionary( g => g.Key , g => g.GroupBy(v => v.START_DATE.Date) .ToDictionary(h => h.Key, h => new { Count = h.Seelct(x => x.ID_OWNER).Distinct().Count()) , TotalTime = h.Sum(h => x.END_DATE-x.START_DATE) } );

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#

Distinct not working with lambda Duplicate drop down list values
you can use GroupBy public IList<ModelSQL.puzzlecontent> GetID(int id) { //for grouping by multiple properties you can use Groupby like // .GroupBy(i=>new { i.WordPuzzleID,i.SecondProperty}) return context.puzzlecontents .Where(i => i.WordPuzzleID == id) .GroupBy(i=>i.WordPuzzleID) .Select(g=>g.First()).ToList(); } or for LINQ to Objects You can use DistinctBy of MoreLinq public IList<ModelSQL.puzzlecontent> GetID(int id) { return context.puzzlecontents.Where(i => i.WordPuzzleID == id).DistinctBy(i=>i.WordPuzzleID ).ToList(); }

Categories : C#

Make list of dictionary from 3 lists where each list data is key in dictionary
What about: from itertools import izip, repeat a = [1, 2, 3] b = ['a', 'b', 'c'] c = ['aa', 'bb', 'cc'] addresses = repeat('address') ids = repeat('id') names = repeat('names') d = [dict(((i, j), (k, l), (m, n))) for i, j, k, l, m, n in izip(addresses, a, ids, b, names, c)] Re: slower - I tried to simply benchmark it: from time import time t = time() for i in xrange(100000): d = [dict(((i, j), (k, l), (m, n))) for i, j, k, l, m, n in izip(addresses, a, ids, b, names, c)] print time() - t gives 0.68 seconds, the OP's way gives 0.81 seconds. Re 2: and the fastest way (and IMHO also simplest) is: d = [{'address': j, 'id': l, 'names': n} for j, l, n in izip(a, b, c)] giving 0.23 seconds.

Categories : Python

convert dictionary values to a list of values python
>>> testDict = {'Mississippi': '28', 'Oklahoma': '40', 'Delaware': '10', 'Minnesota': '27', 'Illinois': '17', 'Arkansas': '05', 'New Mexico': '35', 'Indiana': '18', 'Maryland': '24'} >>> {k: [v] for k, v in testDict.items()} {'Mississippi': ['28'], 'Oklahoma': ['40'], 'Delaware': ['10'], 'Minnesota': ['27'], 'Illinois': ['17'], 'Arkansas': ['05'], 'New Mexico': ['35'], 'Indiana': ['18'], 'Maryland': ['24']} You are getting the too many values to unpack error since the keys in the first dictionary are strings and not lists. The following works. >>> elem = "abc" >>> [elem] = ['abc'] But, this gives an error. >>> [elem] = "abc" Traceback (most recent call last): File "<pyshell#64>", line 1, in <module> [elem] = "abc" Value

Categories : Python

With python, how do I change the values of list using a dictionary
Use a list-comprehension: >>> lis = [['foo', 'foot', 'oot'], ['foo', 'foot', 'oot'], ['bar', 'bart', 'art'], ['bar', 'bart', 'art']] >>> dic = { 'foo' : 1, 'bar' :2, 'foot':34, 'bart':54, 'oot':123} >>> nan = float('nan') >>> [[dic.get(y,nan) for y in x] for x in lis] [[1, 34, 123], [1, 34, 123], [2, 54, nan], [2, 54, nan]] dict.get(key, default_value) : returns the value related to key if the key is found else returns the default_value. We can't use NaN directly in python, that's why used float('nan').

Categories : Python

python: iterating through a dictionary with list values
Here's a speed test, why not: import random numEntries = 1000000 d = dict(zip(range(numEntries), [random.sample(range(0, 100), 2) for x in range(numEntries)])) def m1(d): for k in d: for x in d[k]: pass def m2(d): for k, dk in d.iteritems(): for x in dk: pass import cProfile cProfile.run('m1(d)') print cProfile.run('m2(d)') # Ran 3 trials: # m1: 0.205, 0.194, 0.193: average 0.197 s # m2: 0.176, 0.166, 0.173: average 0.172 s # Method 1 takes 15% more time than method 2 cProfile example output: 3 function calls in 0.194 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.194 0.194 <string>:1(<module>) 1 0.19

Categories : Python

Comapring two dictionary values with keys which are in list
This should do what you need it to do key_to_compare = ['Name', 'num', 'working'] for key in key_to_compare: for d1 in group1: for d2 in group2: if d1[key] == d2[key]: print "same values for %s %s %s" % (key, d1[key], d2[key]) Change the if statement to do what you would like for elements with the same value.

Categories : Python

Dictionary with Multiple Values from a Nested List
This is a case for collections.defaultdict: import collections my_list = [('key1', 'topic1', 'content1'), ('key2', 'topic1', 'content2'), ('key3', 'topic2', 'content3')] my_dict = collections.defaultdict(list) for _, key, value in my_list: my_dict[key].append(value) print(my_dict) Gives us: defaultdict(<class 'list'>, {'topic2': ['content3'], 'topic1': ['content1', 'content2']}) The defaultdict creates the list for the values if it doesn't exist, meaning we can do this really easily by just looping over the list and appending the values to the key. It acts exactly as a normal dictionary in every other way, but if you need a normal dict, you can just use dict() on it.

Categories : Python

how do i call dictionary values from within a list of dictionaries ?
So students is a list of dictionaries. You then want for student in students: print student['name'] Also when you want to call a key in a dictionary you have to put the key name in quotes, as a string: alice[homework] doesn't work because Python thinks homework is a variable. You need alice['homework'] instead. So to look at all of the information nicely, you could do for student in students: for field in student.keys(): print "{}: {}".format(field, student[field]) You can play around to make the formatting nicer, e.g. printing name first, inserting a new line between each new student, etc.

Categories : Python

Replace values in a dictionary with the values from the list
You can add a simple counter (a new variable). i = 0 for key in d: #check if we're not out of bounds if i >= len(list1): break if len(d[key]) == 2: d[key] = [list1[i]] i+=1

Categories : Python

How to convert dictionary values into list in Python / Django?
You need to register your function as a template filter. Also, this code will need to be in a module and then imported into your template as such... # custom_filters.py from django import template register = template.Library() @register.filter def all_numbers(data): number_list=[] if isinstance(data, dict): for name, address in data: for street in data.list(): # this will raise an exception number_list.append(street) return number_list # your-template.html {% load custom_filters %} {{ directory.addressbook.items|all_numbers }}

Categories : Python

Combine/Add dictionaries in a list when the values for two dictionary are equal in C#
var lookup = dicList.ToLookup(x => new{ Product = x["Product"], Region = x["Region"]}); var condensedDicList = lookup .Select(x => new Dictionary<string, object>(){ {"Product",x.Key.Product}, {"Region",x.Key.Region}, {"Profit",x.Sum(d=>(int)d["Profit"])} }) .ToList(); but seriously... why not write a class with class MyData { public string Product{get;set;} public string Region{get;set;} public int Profit{get;set;} } and save yourself a huge amount of ball-ache.

Categories : C#

Retrieve a list of IDs and Values from XML using Linq
Providing this is stored in an XML file: XElement xe = XElement.Load(file); List<int> Ids = new List<int>(); Ids = xe.Elements("item").Attributes("ID").Select (x => XmlConvert.ToInt32(x.Value)).Distinct().ToList(); List<string> Values = new List<string>(); Values = xe.Elements("item").Select (x => x.Value).Distinct().ToList();

Categories : Dotnet

Read list of lists and output as dictionary, the count of values per key
Use a collections.Counter: If I understand correctly, you want to know the number of times each "key" is present. The following code will do that: d = Counter(x[0] for x in list1)

Categories : Python

Rendering dictionary having values in list format in django template
To access array elements on a django template you must refer to them as elem.attribute. In your case, value.0 and value.1. {% for keys, value in url_dict.items %} <tr border = 1px black> <th>{{ keys }}</th> <td>{{ value.0 }}</td> <!--requires value[0] but not working --> <td>{{ value.1 }}</td> <!--not working --> </tr> {% endfor %} This page may help you: Access array elements in a django template Hope this helps,

Categories : Django

Write dictionary values (list) to output file - Python
If I understand what you require correctly then what you need is to replace this expression: str(TermGeneDic[Term]) with something like: " ".join(TermGeneDic[Term])

Categories : Python

Fastest Way to Multiply Dictionary Values and Output to 'list type'
How about [mydict[key]**exp[key] for key in mydict.keys()] assuming mydict and exp both have the exact same keys? Side note: [mydict[key]**exp[key] for key in mydict] does the same thing as above, the .keys() is optional. And if you're concerned with speed use the time module to test the speed of each method as such: import time t = time.clock() for i in range(1000): # your code here, for example: [mydict[key]**exp[key] for key in mydict.keys()] print "time", time.clock() - t

Categories : Python

Select distinct values from a list using LINQ
The way you wrote it you get only exact duplicate lines cut. do you get any of them in your result ? if you need to distinct on specific column check out this answer: Distinct By specific property

Categories : Asp Net

Linq Count Unique Values in List
This will sum up using both the ItemID and ItemDescription values: var x = from order in orders from item in order.OrderItems group item by new { ItemID = item.itemID, ItemDescription = item.itemDescription } into g select new { ItemID = g.Key.ItemID, ItemDescription = g.Key.ItemDescription, Count = g.Sum(o => o.itemQuantity) };

Categories : C#

How to query a Datatable using LINQ and add values to a List?
This can be done using Select and ToList: var lstProductData = dtReport.Rows.Cast<DataRow>() .Select(row => new ProductData(new Guid(row["ProductID"].ToString()) , row["Product"].ToString())) .ToList();

Categories : C#

how to use linq to retrieve values from a 2 dimensional generic list
var smallestGroup = traysWithExtraAisles .GroupBy(x => x.count) .OrderBy(g => g.Key) .First(); foreach(var x in smallestGroup) { var poolTray = x.tray; }

Categories : C#

How to use Intersection between two list for multiple values in linq for unique records
Just slap on a Distinct after the query and you should be fine. var result= (from t1 in DBContext.table1 join t2 in DBContext.table2 on t1.FormNo equals t2.FormNo Where FormTypeList.Contains(t2.FormType) Select new { Form_Id = t1.Form_Id, FormNo = t2.FormNo, FormType = t2.FormType }).Distinct().ToList();

Categories : C#

Python 3: List inside dictionary, list index out of range
Notice that in the first interation of your nested loop, we see the following values that are both in Moves: >>>new_dict[0][1], new_dict[0][3] ('R', 'S') However, on your second iteration in the nested loop, you are trying to evaluate terms that are not included in the dictionary: >>>new_dict[1][5], new_dict[1][7] IndexError: list index out of range Notice that new_dict[1] only has 4 elements: >>>new_dict[1] ['p3', 'R', 'p4', 'P'] So you can only reference new_dict[1][0],new_dict[1][1],new_dict[1][2],new_dict[1][3]: >>>new_dict[1][0],new_dict[1][1],new_dict[1][2],new_dict[1][3] ('p3', 'R', 'p4', 'P')

Categories : Python

using a list of labels and a larger list to create a dictionary in Python
itertools to the rescue! You need both zip/izip and cycle. labels = ('price', 'interest','bid','ask','vol') list2 = ... # whatever you have itertools.izip(labels, itertools.cycle(list2)) Well, zip/izip is maybe not really needed. Depends what you will do...

Categories : Python

Howto transform python list of dictionary to new list of dictonary?
Something like this: >>> from itertools import chain >>> from collections import defaultdict >>> vals = set(chain.from_iterable(y for x in list1 for y in x.values())) >>> dic = defaultdict(list) >>> for x in vals: ... for y in list1: ... for k,v in y.items(): ... if x in v: ... dic[x].append(k) ... >>> dic defaultdict(<type 'list'>, {'e4': ['n3'], 'e1': ['n1', 'n2'], 'e3': ['n1', 'n3'], 'e2': ['n1', 'n2', 'n3']})

Categories : Python

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#

Selecting changes in values with Lambda, Linq, Entity Framework
Edited after reading your dataset again. I see a grouping wouldn't work. Ideally though, you want this logic on the db server, not client side due to network io, etc. You can either write this as a proc or dynamic sql. Dynamic sql maybe easier in the near term. Simple method, select it into a cursor. Loop into a temp table variable and return the result set. If you dataset is really small, then stick with the easy to read linq loop you have. Don't add more complexity unless you need too. i.e. don't micro-optimize.

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#



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