c# - Error on CSV to Dictionary -
not sure why isn't working, it's adapted code work. looks need explicit cast i'm not sure why or put it. error is:
"cannot implicitly convert type 'system.collections.generic.ienumerable{system.collections.generic.dictionary{string,string}}' 'system.collections.generic.dictionary{string,string}'"
public static dictionary<string, string> data_entry(string dataentity, string datacategory, string datastream = "") { var lines = file.readalllines(@"c:\myfile.csv"); var header = lines.first().split(','); return (from line in lines.skip(1) let cols = line.split(',') cols[0].toupper() == dataentity & cols[1].toupper() == datacategory & cols[4].toupper() == datastream select header.select((h, i) => new { header = h, index = }) .todictionary(o => o.header, o => cols[o.index]) ); }
your linq query returning ienumerable<t>
object t of type dictionary instead of expecting dictionary.
if understand code want create list of dictionaries column header key , line's column index value value. since dictionaries cannot have duplicate keys, can't turn entire thing 1 dictionary object there exceptions duplicate keys.
so want pull todictionary() call out of linq statement , apply result of linq statement instead dictionary. unfortunately, result in said duplicate key errors way it's coded instead of returning dictionary might consider different datastructure or change return type ienumerable<dictionary<string,string>>
type.
edit: based on follow-up information in comments following need be. notice added firstordefault() call results of linq query. means return first result (which type dictionary<string,string>
) satisfies method's return type. it's worth having check in calling code null return in case if you're confident never null.
public static dictionary<string, string> data_entry(string dataentity, string datacategory, string datastream = "") { var lines = file.readalllines(@"c:\myfile.csv"); var header = lines.first().split(','); return (from line in lines.skip(1) let cols = line.split(',') cols[0].toupper() == dataentity & cols[1].toupper() == datacategory & cols[4].toupper() == datastream select header.select((h, i) => new { header = h, index = }) .todictionary(o => o.header, o => cols[o.index]) ).firstordefault(); }
Comments
Post a Comment