Linq To Objects - (C#) Creating A Dictionary From An Existing List Without Looping?
Aug 31, 2011
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 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 procedure in VB.net using VS.net 2008 which will get the list of Orders and build a XML file with the list of Orders as shown in the code below: As the number of Orders is getting huge, I want to build the XML file for every 500 Orders
[Code]....
Instead of building XML for all the records I want to create XML for each 500 records. I tried the following code and it is throwing an error saying Expression is of type Orders which is not a collection type.
How can I get a new distinct list from an existing list using LINQ? This is what I have so far and it is not distinct but does give me a new list.
Dim tmpQryColumn = (From a In _allAudits Select New CheckBoxListItem With {.Id = a.AuditColumn, .Name = a.AuditColumn} ).Distinct() _columnList = New List(Of CheckBoxListItem)(tmpQryColumn)
Is there any way to use a LINQ to XML to query an XML document like the one below to create new (anonymous or strongly typed) objects from the child elements of a descendant? Here is my XML document:
I am in the process of learning LINQ to Objects. I am querying an array of reference elements using LINQ. In the code below, which I have marked with asteriks and PROBLEM, I am having difficulty returning any values for and I suspect its because of the multiple Select arguments.
'Program name:Querying an Array of Invoice Objects 'Created/revised: 'Project description:To demonstrate the use of LINQ to query objects
I have a list of objects, each with 2 relevant properties: "ID" and "Name". Lets call the list "lstOutcomes".I need to check the list for duplicates (meaning object1.ID = object2.ID, etc.) and set a flag (valid = false, or something) if there is at least one duplicate. Also, it would be nice to send a message to the user mentioning the "Name" of the object, when it fails.I am sure I will need to use the Group By operator to do this, but I am not used to doing that in LINQ, and the examples out there are just not helping me. This article seems to be close to what i need, but not quite and it's in C#.
Here is a starting stab at it... Dim duplist = _ (From o As objectType In lstOutcomes _
I 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.
Dim l as IList(Of Foo) = (From dataRow As DataRow In table.Select() Where CStr(dataRow("Column1")) = "A" Select New Foo(CStr(dataRow("Column1")), _ CStr(dataRow("Column2")))).ToList()
What's happening is that if i set a break-point to the constructor of Foo and step, the constructor is hit and the parameters are loaded with the arguments. However, l has empty Foo objects (the members in every object are Nothing). What could be happening here?
Dim objectsList as List(Of Object) = GetAllObjects() ' Filter from Objects just Persons ' Dim peopleList as List(Of Person) = ???
What is the most efficient and effective LINQ expression to do it?
EDIT
1 Dim selectedObjects As List(Of Object) = GetAllObjects()
2 Dim selectedPeople As IEnumerable(Of Person)= selectedObjects.OfType(Of Person)
3 Dim people As List(Of Person) = selectedPeople.ToList()
Error on 3:
Value of type 'System.Collections.Generic.List(Of System.Collections.Generic.IEnumerable(Of Person))' cannot be converted to 'System.Collections.Generic.List(Of Person)'.
I figure I should use 'Aggregate' but apparently I am getting it wrong First I get a list of my Entity objects Dim employers As List(Of myEntity) = (New XXXX()).getZZZ(userName, userType) Then I figured this would be a way to put all the names in a string Dim names as String = employers.Aggregate(Function(current, [next]) current.Name & " " & [next].Name)
Basically, I am trying to write a LINQ to Objects statement where the relationship is a grandparent, parent, child relationship. (You could also call it a Master Detail relationship.)
In Legacy code here is a simplified version what I am trying to accomplish. Dim coverages As New List(Of Coverage) Dim coverage As Coverage For Each rl In oClaimsPolicy.RiskLocations coverage = New Coverage coverage.Level = "Location" [Code] .....
If is it not clear one Location can have many Items and one Item can have many Coverages. I basically want to list the items and show the relationship between grandparent (Location), parent (Item) and child (Coverage).
I am having so trouble with the ToUpper() procedure with strings. I am using LINQ to find unique values in a list of objects. In that whole process I set the values to compare to all lowercase in order to get a proper list. My goal is to populate a dropdown list with the values. I'm attempting to set the first letter of of the string to uppercase and keep the rest lowercase however the toUpper() procedure is not working?
Private Function FixCase(ByVal strIn) As String Dim strOutput As String Dim intStringLength As Integer = strIn.Length - 1 strOutput = strIn.Substring(0, 1)
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)
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
I have a process that imports a daily file of product registrations, and adds them into our database. Originally this process would query against the database multiple times for each record to determine how to process the data.In order to speed up this process and prevent any timeout issues that could appear to people trying to use a reporting site that uses the same database, I've changed the code to pull down a few of the tables into dictionaries, and then iterate across them to see if that customer/address/dealership exists, and pull the Id from the key of the dictionary if it does, or insert it into the table and then the dictionary if it doesn't.However, I'm currently finding this to be running slower than if I were querying the database multiple times for each registration. One possible cause that I can think of is that my dictionaries are quite large (one has 8 million entries and another has 11 million).[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.
I have some code that I want to apply to many objects (Pictre Boxes) and I was unable to loop through the objects via a For loop and am currently forced to copy paste the code for each Image Box.
The Pictre Boxes are named compAlien1, compAlien2 ... compAlien9
Is there a way to do something similar to this:
For i = 1 To 10 Step 1 compAlien[i]... #code# Next i
ArialRegular8 | <Corresponding Font Object> ImpactItalic10 | <Corresponding Font Object> TimesRomanRegular12 | <Corresponding Font Object>
These font types come from an external library, the real type is DocumentFont, I prefer not to store just values and recreate the font object later, so I need to store the object, and i want to be able to call Contains() later without looping. like for example Dictionary (of T Key, T Value), is this the best option? Also, to be able to call Contains(), i will have to overload function Contains() using an Interface or this is already built-in in some Collections / Dictionaries when using a String as Key?
I'm having trouble implementing an IComparer method. Essentially, I want to compare the properties of two custom objects (the properties are of type integer).dE is a Dictionary(Of String, customObj)prTabIndex is a property of customObj and is of type Integer (these hold true for all examples)After some more searching I found this thread which suggested 3 things: a List approach, utilizing LINQ, and using some C# 3.0 features. I've tried three different ways:...rolling my own IComparer implementation:
Public m As Sub(ByRef d As Dictionary(of String, customObj)) Dim sortedD As New SortedDictionary(Of String, customObj)(d, myCompare) End Sub
[code]....
Note that VS2008 has underlined 'dE.ToDictionary...' (to the end of the line) and giving me two messages depending on where I hover my mouse:
1) "Data type(s) of the type parameter(s) in extension method 'signature' As 'signature defined in 'System.Linq.Enumerable cannot be inferred from these arguments. Specifying the data types explicitly might correct this error. Seen while hovering over "ToDictionary".
2) Nested function does not have the same signature as delegate 'signature'. Seen while hovering over anything after "ToDictionary".
Q1) How far off am I in each of the implementations?
Q2) Which one is the computationally least expensive? Why?
Q3) Which one is the computationally most expensive? Why?
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.
As 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.