Avoid For Loop (Dictionary Array) Using LINQ?
Nov 23, 2010How to avoid for loop (Dictionary Array) using LINQ
View 1 RepliesHow to avoid for loop (Dictionary Array) using LINQ
View 1 RepliesI want to group items from a linq query under a header, so that for each header I have a list of objects that match the header title. I assumed the solution would be to use ToDictionary to convert the objects, but this allows only one object per "group" (or dictionary key). I assumed I could create the dictionary of type (String, List Of()), but I can't figure out how to write it. As an example I have written a simplified version below.
[Code]...
I have the following object:
countDictionary As Dictionary(of Category, Dictionary(of Date, Integer))
The Class has a Enumeration Property. For the purposes of demonstration, I'll call it MasterCategory.I have been trying to get out an object that looks like the following:
groupedCountDictionary As Dictionary(of MasterCategory, Dictionary(of Date, Integer)
The best result I could get was:
Lookup(of MasterCategory, Dictionary(of Date, Integer))
From:
countDictionary.ToLookup(Function(o) o.Key.MasterCategory, Function(o) o.Value)
Which results in a IEnumerable (Of Dictionary(of Date, Integer)) for each MasterCategory value.However, I need that IEnumerable of Dictionary flattened to one dictionary with all the integers summed (total counts) for each date. I then tried to use various selects and group bys (from numerous stackoverflow posts) to "flatten" it, but my efforts have fallen short.
Current Code
[Category Class]
- MasterCategory As Enum
- Name As String etc
[code]....
I have created a Dictionary class (MyDictionary for the example). I am currently trying to pass MyDictionary into a function, filter it into a new instance of MyDictionary and pass this new instance into another method. When I am attempting to create the second instance from the filtered first instance of MyDictionary via Lambda Expressions and the ToDictionary Method, I am getting the following error:
Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.Int32,System.String]' to type 'MyDictionary'. I have simplified the example and recreated it in LINQPad and am getting the same error.
Here's the simplified version of my code:
[Code]...
I'm trying to sort a dictionary by value with LINQ but I can't figure how the ToDictionary() method works.
All the examples I can find are in c#.
here's my code
Dim f As Dictionary(Of String, String) = (From value In projectDescriptions.Values
Order By value Ascending
Select value).ToDictionary(???)
[Code].....
In My Code i am using Dictionary(Of String , String) As Key Value Pair ..While i am using LINQ to Query this Dictionary, It Shows Dictionary is not Queryable.
View 1 RepliesAs I am beginner in LINQ, I have small problems. I have dictionary of Char and Long, and I would like to use LINQ to retrieve Char with highest Long Value. I saw some C# samples, which look pretty easy, but I can't achieve such expression in VB.Here are two expressions, and I don't think they are most efficient possible.
[Code]...
This should be extremely simple but I'm still new to the language and don't grasp the basics yet.
[Code]...
I need a simple LINQ query on VB.NET on the dictionary [Code] What I need here is to retrieve a SINGLE website (dictionary value of string type) or NOTHING (if the query cannot find an affordable result) given those rules: The dictionary key (integer) must be greater than startSite and not equal to mainSite or returnSite (both must be excluded from the result) Any hint? [Code]
View 2 RepliesI have a dictionary collection as bleow:
mydic.addvalue(key1, val1)
mydic.addvalue(key2, val1)
mydic.addvalue(key3, val1)
mydic.addvalue(key4, val2)
mydic.addvalue(key5, val2)
From the above dictionary I want to delete all the entries where value == "val1", so that the result would have only following entry:
mydic.addvalue(key4, val2)
mydic.addvalue(key5, val2)
My VB source code is on VS2008 and targeted for 3.5
I have a Dictinary(Of String, Item) and I'm trying to sort it into alphabetical order by the item name. I don't want to use a sorted dictinary and without it, I've having zero luck. Linq is not my strong point.
[Code]...
I've got a Dictionary(Of SomeEnum, Integer) that gets filled up while looping through some objects that have a property with type SomeEnum. Once the loop is done, I want the SomeEnum type that occurs the most in the list of objects. I also need the other counts as well for display purposes, hence the usage of a simple Dictionary(Of K, V).I am looking for a LINQ query to give me back the SomeEnum key that occurs the most by looking at each keys number of occurences. Or perhaps there's an easier way of going about it.I could do this:
Return (From kvp As KeyValuePair(Of SomeEnum, Integer) _
In Me.MyObjects Order By kvp.Value Descending _
Select kvp).First().Key
But wouldn't the sorting be a more expensive operation than trying to wiggle Max() in there somehow?
I am trying to populate a dictionary with objects created from data in a recordset, but am having difficulty with VB's object referencing. I am very new to VB. Pseudo code of what I am trying to do:
dim dict as Dictionary
rs = getRecordSet
while rs.moveNext
set myObj = new MyClass
myObj.properties = rs.relevantFields
dict.add myObj.getUniqueKey, myObj
wend
However, all 'objects' in the dictionary are actually references to the most recently created (and thus last) object in the dictionary. I know why what I am doing above is not working, but I don't know the correct way to do it so that each element in the dictionary is it's own object.
I have a collection as follows
Private _bankRates As Dictionary(Of RateSourceBank.Key, RateSourceBank)
Where RateSourceBank.Key is simply
Public Class Key
Public RateType As String
Public EffectiveDate As DateTime
[Code].....
I have the following in VB:
Dim sources = From source In importSources Select New With _
{.Type = source.Key, .Source = source.Value.Name}
dgridSourceFiles.DataSource = sources
[code]....
I don't know if this is doable, maybe with Linq, but I have a List(Of MyType):
Public Class MyType
Property key As Char
Property description As String
End Class
And I want to create a Dictionary(Of Char, MyType) using the key field as the dictionary keys and the values in the List as the dictionary values, with something like:
New Dictionary(Of Char, MyType)(??)
Even if this is doable, internally it will loop through all the List items, I guess?
I have a generic dictonary which is templated in the following manner:
[code...]
If I wanted to omit certain list items against arbitrary keys (that is the items that are in the list contained within the value part of each of the key value pairs making up the dictionary) given some arbitrary condition (lets say omitting list items where a list item contained the string "abc")
I would expect to able to create/project into a new dictionary which would contain entries which contained lists WITHOUT those items whose name contained "abc"
How do I achieve this using a Lambda expression?
I was trying something like this:
[code..]
I have been trying to use a bit array as a dictionary key and even though I know each bitarray value is different the program fails with a duplicate key message when a try to add the second record to the dictionary. Is there any way I can make this work?
View 2 Replies Dim AttributeValuePairs() As Dictionary(Of String, String) = New Dictionary(Of String, String)
byt this i mean AttributeValuePairs is a Array of dictionaries
[code]......
I have the following code, where I am trying to use returned JSON data, deserialize it, and return 1 part of that data back to the user.
<%@ Page Language="VB" Debug="True" EnableViewState="false" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>
<script runat="server">
Class Item
Public Property some_number() As Double
[Code]...
I don't understand how to deserialize into the Item class, then how to get the data back out.
I am trying to deserialize a JSON string that looks like so: {'type':'clientlist','client_list':[]} I am using JavaScriptSerializer() to do it. For some reason the JavaScriptSerializer() is choking on the member 'client_list'. It doesn't give very good info. The error it gives is:
[Code]...
I have two classes, one nested in the other. [code]Neither "Name" or "ID" are unique between operations and records.I wish to construct a dictionary using LINQ = Dictionary(Of String, Of List(Of Integer), whereby the keys are uniqe examples of Names in my collection and the values are the collective set of distinct IDs that are associated with those names.
View 2 RepliesCan this be rewritten any better using LINQ? I'm a C#er trying to think in VB.NET for this current project. It's in an ASP.NET Web Forms .vb codebehind:
Public ReadOnly Property AllowedCategoryIds As Integer()
Get
Dim ids = New List(Of Integer)
[Code]....
I have a LINQ2Entity problem, I want to get the value, string, from a database, so I select FProducts.Serial_number, and to end the query, I do .ToDictionary. The problem is, it tells me that it doesn't have sufficient parameters, to convert ToDictionary. So I need something like select FProducts.Serial_number, Nothing). ToDictionary. Also FProducts.Serial_number, 0).ToDictionary doesn't work.
Sub GetStatistics(ByVal ProductNumbers As List(Of String), ByRef Passed As Integer, ByRef FailedProducts As List(Of String))
Passed = 0
FailedProducts = Nothing
[Code]...
I need small code for array/dictionary to pullout data conditionally.i have data:
oid----opriority----task
10--------3-------Task1
5--------1--------Task2
1--------6--------Task3
i need to build one array/dictionary to store the data in this format then i can pull the value like.
select oid where task = task1 order by opriority
It is easy for me do in database table, This is run time and i need to work in RAM. how i can build the array and pull the data accordingly.
I've got some code to try and loop through LINQ results, but it doesn't seem to be working.
HERE'S THE CODE
Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest
''# the page contenttype is plain text'
[Code]....
Here's my query dim areas = From job In db.jobs Join area In db.areas
On area.JobID Equals job.JobID
Where job.JobID = id
Select area.Area, area.UnitID
I have two controls in my form
2 textboxes: tbArea1 and tbArea2
2 comboboxes: cbArea1Units and cbArea2Units
I've traditionally used a ForEach loop to cycle through LINQ to SQL results, but this instance doesn't seem to work. By design in the database, the result will always only return up to two possible areas, but no more then that. How can I populate the textboxes and set the SelectedValue of the comboboxes to something like this?
[Code]...
I have created a class with a function in it. I have a collection of data I want to pass back. I tried an arraylist first. Now I am trying to use a dictionary. My problem is that it creates the dictionary ok, but I am only get the last row of data from my
Function GetWeldAuditInfo(ByVal ResourceId
As
String,
ByVal VendorId
[CODE].........................
I am writing code that pulls data from database tables and writes them to an XML file (to be picked up by another process). There are bout 60,000 records, and each record can have multiple entites, i.e. a member can have several contacts, each contact can have several phone numbers, etc. The entire process takes several hours, and I've narrowed down the slowness to the actual pull of the data (not writing the XML, or any data processing after it's pulled, etc.). I've tried the code two different ways, with similar results. First I leveraged LINQ queries and created all the elements in one statement:[code]That produced almost no change in amount of time the process took. I then tried stripping out all the elements and reduced the code down to just the database pulls, and it was similarly slow.Is there a faster/better way to pull all this normalized data from the database so I can get it to the XML file as quickly as possible?
View 3 RepliesI have the following code:
Dim i As Integer
For i = 1 To 20
Dim captionTextBox As TextBox = DirectCast(Me.FindControl("news_Image" +
[Code].....
Where the comment is in the code above, I need to insert the value of the textbox (text) into Linq columns. For example: articleToUpdate.news_Image1Caption, news_Image2Caption, but I need to change the number after news_ to the value of i in the for loop.