开发者

Filling a multi-value dictionary with query results

开发者 https://www.devze.com 2023-03-26 08:26 出处:网络
I am retrieving five columns through an SQL query. Among the columns retrieved, I have a column RecordID which should act as a key to a dictionary.

I am retrieving five columns through an SQL query. Among the columns retrieved, I have a column RecordID which should act as a key to a dictionary.

I am referring to the solution posted: C# Multi-Value Dictionary at StackOverflow, but I am not able to use it effectively depending upon my situat开发者_如何学运维ion.

I want to store all the rows of my query but the RecordID column should also act as a key to the dictionary element. I want something like:

Dictionary<RecordID, Entire columns of the current row for this RecordID>

An alternative I think is to use an array, something like:

Dictionary<key,string[]>

But I want to use any super-fast way.


Use a Lookup - you haven't said much about the data, but you may need something as simple as:

var lookup = list.ToLookup(x => x.RecordID);

There are, of course, overloads for ToLookup which allow you to do other things.


Oh goodness sake, you need a dedicated class to hold the values. Since the columns are from a db table the number of fields is fixed. Hence you can have a class with fixed fields rather than a dynamically growing collection. And lastly use a KeyedCollection<TKey, TItem> structure to hold a collection of records. In a KeyedCollection<TKey, TItem> the TKey part is embedded in the TItem, in your case its RecordId.

class Record
{
    public int Id { get; set; }
    //rest of the fields
}

Your structure should look like KeyedCollection<int, Record>. It preserves insertion order as well. You can query the collection using RecordId via indexer, just like a dictionary.

0

精彩评论

暂无评论...
验证码 换一张
取 消