简体   繁体   中英

Dictionary <string, uint> to comma-separated string?

// Below is an array which contains master data
string[] masterData = { "324", "233", "32", "423", "23435" };

// Below string will always contain a comma separated subset of above master data
string abc = "233,423,99";

What I need is to have a dictionary having string key of all masterData array values & have the value set to 1 only for those keys which are in the string abc. All other keys need value of 0. In this case, dictionary should be of type string & value should be of type uint. In this case, dictionary should be as shown below:

String   uint
 "324"   0
 "233"   1
 "32"    0
 "423"   1
 "23435" 0

Note that 99 from string is ignored as only all master data should be present in dictionary.

Is there a way to do it using linq? If not, what other shorted way is it possible with?

Also, how do I perform the above operation in the reverse way using linq or any other shorted approach ie convert dictionary<string, uint> back to comma separated string? And this string should contain only those keys from the dictionary whose value is 1.

Note: dictionary value can be either 1 or 0 only.

Any help is much appreciated.

var abcArray = abc.Split(',');
masterData.ToDictionary(p => p, p => (uint)(abcArray.Contains(p) ? 1 : 0));

You can use Concat to add together the first array and the split string, then use GroupBy to group the same numbers, then just create the Dictionary from that, the duplicated items will have a Count greater than 1.

 var dict = masterData
            .Concat(abc.Split(','))
            .GroupBy(x => x)
            .ToDictionary(k => k.Key, v => v.Count() > 1 ? 1 : 0);

To reverse, select all the strings where the Value is 1 and Join the sting

string result = string.Join(",", dict.Where(x => x.Value > 0)
                                     .Select(k => k.Key)
                                     .ToArray());

string abc = "233,423,99"; var subset = abc.Split(','); var result = masterData.ToDictionary(k => k, k => Convert.ToUInt32(subset.Contains(k))); var reversedResult = result.Where(p => p.Value == 1).Select(p => p.Key).ToArray();

https://dotnetfiddle.net/5eU5B0

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