Convert Linq Query Result to Dictionary

Convert Linq Query Result to Dictionary

Try using the ToDictionary method like so:

var dict = TableObj.Select( t => new { t.Key, t.TimeStamp } )
.ToDictionary( t => t.Key, t => t.TimeStamp );

I want to convert my LiNQ result to Dictionary

Try this code:

var result = new { firstname = "Mary", lastname = "Poppins", NPI = "NPI" };

var dictionary =
result
.GetType()
.GetProperties()
.Where(x => x.PropertyType == typeof(string))
.Select(x => new { x.Name, Value = (string)x.GetValue(result) })
.ToDictionary(x => x.Name, x => x.Value);

I get:

dictionary

Returning a Dictionarystring, string from a linq query

Try this:

var dict = TheTable.Select( t => new { t.Col1, t.Col2} )
.ToDictionary( t => t.Col1, t => t);

Remember in select lambda you will perform projection and create some anonymous object. Then in ToDictionary you will pass two parameters: First Parameter is a lambda to specify the key; in code above we are choosing Col1 to be the key. Second parameter is a lambda to specify the value; in code above we are choosing the object itself to be the value.

If you want the value to be an anonymous type, change the 2nd lambda like this:

ToDictionary( t => t.Col1, t => new { t.Col2 });

If you want the value to be a type you have defined, change the 2nd lambda like this:

ToDictionary( t => t.Col1, t => new YourType { Prop1 = t.Col2 });

converting linq result to dictionarystring, int

Your query is attempting to query from the dictionary, which is returning a KeyValuePair when you use select c. You just need to generate a Dictionary from the table, so try this instead:

var result = db.Countries.ToDictionary(c => c.LocationName, c => c.ID);
aqfv.Location = result;

LINQ query to return a Dictionarystring, string

Use the ToDictionary method directly.

var result = 
// as Jon Skeet pointed out, OrderBy is useless here, I just leave it
// show how to use OrderBy in a LINQ query
myClassCollection.OrderBy(mc => mc.SomePropToSortOn)
.ToDictionary(mc => mc.KeyProp.ToString(),
mc => mc.ValueProp.ToString(),
StringComparer.OrdinalIgnoreCase);

convert query result to dictionary in vb.net

As you do not have a special projection in the select, you can just call ToDictionary on the collection. The first lambda expression retrieves the key, the second one the value.

Dim dicQuery = toolkitEntities.currentfrontcommoditysymbols.ToDictionary( _
Function(x) x.ShortDesc, _
Function(y) y.CurrentFrontSymbol)

As for your update: the following query should get you the desired result:

Dim query = (From d In ctx.projections
Where d.SymbolId <= 42 AndAlso d.Date >= lookbackDate
Join t In ctx.symbols On d.SymbolId Equals t.Id
Let actualRange = d.HighProjection - d.LowProjection
Select New With {
d.Date,
d.SymbolId,
t.Name,
actualRange}).GroupBy(Function(o) o.SymbolId)
.ToDictionary(Function(p) p.Key,
Function(x) x.Select(Function(y) New ProjectionPerformance() With {
.SymbolId = Convert.ToInt32(y.SymbolId),
.ProjectionDate = y.Date.ToString(),
.Name = y.Name,
.ProjectedRange = y.actualRange
}).ToList())

Building LINQ query to get List of Dictionaries from Dictionary of string/HashSet of Dictionary of String/String?

You can use SelectMany to get the dictionaries in each Value:

 matched = myData
.SelectMany(kv => kv.Value)
.Where(dict => dict.TryGetValue(givenKey, out string value) && value == givenValue)
.ToList();

Whenever you see a nested foreach the LINQ way is to use SelectMany.

Your query doesn't work because you are selecting the KeyValuePairs instead of each Values dictionary and also because you pass an enumerable to Where instead of something that returns a bool(a so called predicate).

IDictionary extension not actually running while in LInq Query .Where()

Continuing on my comment, and as @Kirk Woll pointed out, this is an example of a
"deferred execution". In simple words the execution of Where method is delayed until you would need that data.

In your case, you have following code:

    var newItems = fromImport
.Where(i => !items.ContainsKeyIgnoreCase(i.Key))
.Select(i => i.Value);

fromImport
.Where(i => items.ContainsKeyIgnoreCase(i.Key))
.ForEach(i => { i.Value.ID = items.AtKey(i.Key).ID; });

return newItems;

in this moment of execuion there is nothing that accessing the data itself, you do return it, but not interacting.

if you create and test this example (breakpoint is at return in where):

Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("a", 0);
dict.Add("b", 0);
dict.Add("c", 0);

dict.Add("A", 0);
dict.Add("B", 0);
dict.Add("C", 0);

var newItems = dict
.Where(i => {
return !dict.ContainsKeyIgnoreCase(i.Key);
})
.Select(i => i.Value);

Thread.Sleep(10000);

Console.WriteLine(newItems.Count());

you will see that the breakpoint will not be hit until 10 seconds mark
(loot at this screenshot: https://imgur.com/a/uPaAOvS)

As to you comment about breakpoint is never hit, make sure you return a reference to a enumerable rather than a copy, and if you actually interact with it.

As a crude solution, you could make this change to your code:


var newItems = fromImport
.Where(i => !items.ContainsKeyIgnoreCase(i.Key))
.Select(i => i.Value)
.ToList();

this will force the execution of your query, because data needs to be copied into new list

LINQ query to dictionary

got it working.

var browser = (from tbf in context.tblFeedBacks
where tbf.email == dboard.userEmail
select tbf).GroupBy(l => l.browser)
.Select(g => new
{
browser = g.Key,
count = g.Select(l => l.browser).Count()
}).ToDictionary(x => x.browser, x => x.count);

Add to Dictionary Query Results of Multiple Linq Queries

Try this:

Dictionary<string, string> dict = new Dictionary<string, string>();        
foreach (var a in ctx.tbl1.Where(a => a.Id == cid)) dict.Add(a.FieldName, a.LabelName);
foreach (var a in ctx.tbl2.Where(a => a.Id == cid)) dict.Add(a.FieldName, a.LabelName);
foreach (var a in ctx.tbl3.Where(a => a.Id == cid)) dict.Add(a.FieldName, a.LabelName);
return dict;

A few things to consider, though:

This will throw if the same (case-sensitive) a.FieldName appears in more than one table or more than once in the same table for a given a.Id.

Does the underlying DB have constraints to prevent this from happening? If probably ought to, unless the nature of the data is such that one a.FieldName could legitimately appear more than once for a given a.Id. In that latter case, mapping them into a ILookup may be more appropriate.

If a.FieldName is not case-sensitive, create the dictionary with a case-insensitive string comparer.

If uniqueness of a.Id,a.FieldName applies across the aggregate of the 3 tables, would it make more sense for them to be replaced with a single table?



Related Topics



Leave a reply



Submit