Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Populate a Dictionary
Message
General information
Forum:
ASP.NET
Category:
LINQ
Environment versions
Environment:
C# 2.0
OS:
Windows XP SP2
Network:
Windows 2000 Server
Database:
MS SQL Server
Miscellaneous
Thread ID:
01504070
Message ID:
01504081
Views:
58
>Hi All, just in the middle of a code review and I'm finding lots of methods in different classes that use the following method for populating Dictionary and List objects - I'm wondering if there is an easier / generic way using Linq ( It looks like a black art to me ) this is what I have at present
>
>
>DataSet ds = SomeMethodThatReturnsADataSet("MyDS");
>Dictionary<string,string>  MyDictionary = new Dictionary<string,string>(StringComparer.CurrentCultureIgnoreCase);
>
>foreach(DataRow dr in ds.Tables[0].Rows)
>    MyDictionary.Add(dr["KeyName"].ToString(),dr["KeyValue"].ToString());
>
>
>
>which is pretty basic and clean but , this code is scattered among dozens of classes - any thoughts very welcome

Don't think you can use Linq to directly construct the Dictionary. But, if the variables are basically the DataTable and the two Column names then you could make it more generic. Something like:
public IEnumerable<KeyValuePair<string,string>>  GetEntries(DataTable dt, string keyField, string valueField)
        {
            foreach (DataRow d in dt.AsEnumerable())
            {
                yield return new KeyValuePair<string, string>(d[keyField].ToString(), d[valueField].ToString());
            }
        }
which could then be called as:
foreach (var v in GetEntries(ds.Tables[0], "KeyName", "KeyValue"))
            {
                MyDictionary.Add(v.Key, v.Value);
            }
Not much benefit there as is but if you ever needed to do things like selectively filtering the list it could be more useful. e.g:
var v2 = from x in GetEntries(dt,"KeyName","KeyValue").Where(x=>x.Value.StartsWith("Fred")) select x ;
            foreach( KeyValuePair<string,string> xx in v2)
            {
                MyDictionary.Add(xx.Key, xx.Value);
            }
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform