简体   繁体   中英

Adding two comma separated datatable cells to dictionary in C#

I have a datatable where I'm currently storing values from it like this:

string actualprodrow = "PRODUCT";
string actualprod = (from DataRow dr in wafercond.Rows where (string)dr["Parameter"] == actualprodrow select Convert.ToString(dr["Value"])).FirstOrDefault();

Since the order of terms in the table can change I'm searching for the given term and then storing the value for said term. Recently there became a need to store two different comma separated lists in this table that I need to store and associate together. The two rows in the table that are pertinent look like this:

在此处输入图片说明

I need to store the values in the way so that operation 12348 is associated with a 10 offset and 84321 is associated with -20 offset. I know I should store these in a dictionary with operation being the key and offset being the value but I haven't found a way to do this yet. I know it should follow something along these lines that a coworker sent from one of his projects:

Dictionary<string, string> offsets = t.Select(item => item.Split(',')).ToDictionary(s => s[0], s => s[1]);

Any help as to how to get this done would be great appreciated.

I don't think I have a good handle on what you're doing, so this is a rough suggestion. I would maybe get your Operations first and put those into a dictionary, then get your offsets and split them into a list. Loop thru and using an index set the value of the dictionary based on the offset.

string actualprodrow = "Operation";
string actualprod = (from DataRow dr in wafercond.Rows 
                        where (string)dr["Parameter"] == actualprodrow 
                        select Convert.ToString(dr["Value"])).FirstOrDefault();

var operationDictionary = actualprod.Split(new string[]{","}, StringSplitOptions.RemoveEmptyEntries).ToDictionary(key => key, v => string.Empty);

actualprodrow = "Offset";
actualprod = (from DataRow dr in wafercond.Rows
                     where (string)dr["Parameter"] == actualprodrow
                     select Convert.ToString(dr["Value"])).FirstOrDefault();

var offsetSplit =  actualprod.Split(new string[]{","}, StringSplitOptions.RemoveEmptyEntries).ToList();

for (int i = 0; i < operationDictionary.Keys.Count; i++)
{
    var key = operationDictionary.Keys.ElementAt(i);
    operationDictionary[key] = offsetSplit[i];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM