Ashu Rawat
Ashu Rawat

Reputation: 21

Storing result of linq in keyvaluepair with key and value after spliting the String using comma seperator

I am not able to get the result what i am required Please go through this.

I am calling liq query which will give me result like

"99,85,34,20,1,0.5" as key
"5000199,5000185,5000134,5000120,5000101,5000005"

I want this to be like key and value format after spliting them...Like

key            value
99             5000199
85             5000185

in list like key should be 99 and value for this should be 5000199 second key should be 85 and value for this should be 5000185

Query i am using is

var pp = (from a in dc.MediaTypeMasters 
         where a.MediaTypeID == 153 && 
               a.ContentTypeForBilling == "valuepack" 
        select new KeyValuePair<String, String>
                               (a.PartialPricePoints, a.ContentTypeID))
               .ToList();

Like this.

Upvotes: 0

Views: 548

Answers (4)

MarcinJuraszek
MarcinJuraszek

Reputation: 125660

Use Zip method from LINQ:

var keys = "99,85,34,20,1,0.5";
var values = "5000199,5000185,5000134,5000120,5000101,5000005";

var results = keys.Split(',').Zip(values.Split(','), (k, v) => 
                        new KeyValuePair<int, int>(int.Parse(k), int.Parse(v)));

You can then create Dicrionary<int, int> as well:

var dict = results.ToDictionary(x => x.Key, x => x.Value);

Upvotes: 4

Dmitry
Dmitry

Reputation: 654

Make things simple.

Use

var pp = (from a in dc.MediaTypeMasters where a.MediaTypeID == 153 && a.ContentTypeForBilling == "valuepack" a).ToList();

Then you can do

var dictionary = pp.ToDictionary(p => p.PartialPricePoints);

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460288

So basically you want key-value pairs according to their index in two collections?

string[] first = str1.Split(',');
string[] second= str2.Split(',');
IEnumerable<KeyValuePair<string, string>> pairs = first
    .Select((s, i) => new KeyValuePair<string, string>(s, second.ElementAtOrDefault(i)));

Note that Enumerable.ElementAtOrDefault returns null if the second collection doesn't contain as many items as the first.

Upvotes: 1

Hossain Muctadir
Hossain Muctadir

Reputation: 3626

    string key = "99,85,34,20,1,0.5";
    string val = "5000199,5000185,5000134,5000120,5000101,5000005";

    var keyArr = key.Split(',');
    var valArr = val.Split(',');
    var dictionary = new Dictionary<string, string>();
    for (int i = 0; i < keyArr.Length; i++)
    {
        dictionary.Add(keyArr[i], valArr[i]);
    }

Upvotes: 0

Related Questions