Aggregate 2 vocabulary elements per object

I have a dictionary containing the answers to the assessment as follows:

{
    {"question1", "7"},
    {"question1_comment", "pretty difficult"},
    {"question2", "9"},
    {"question2_comment", ""},
    {"question3", "5"},
    {"question3_comment", "Never on time"},
}

but I need to combine the rating item with the comment item into an object as follows

{
    {"question1", "7", "pretty difficult"},
    {"question2", "9", ""},
    {"question3", "5", "Never on time"},
}

It seems to me that I need to use the Aggregate method for this, but I do not know where to start.

+4
source share
4 answers

You can do it as follows:

var res = data
    .Keys
    .Where(s => !s.EndsWith("_comment"))
    .Select(s => new[] {s, data[s], data[s+"_comment"]})
    .ToList();

IDs must first filter out all keys that do not end with "_comment", and then use these keys to find two pieces of content in the resulting array.

Demo version

+5
source

Unconfirmed but maybe a good idea:

Regex r = new Regex("^question\\d$");
var result = myDict.Where(x => r.IsMatch(x.Key)).Select(x => new {
        Question = x.Key,
        Score = x.Value,
        Comment = myDict[x.Key + "_comment"]
});

DasBlinkenLight. , ^question\d$ ( , ). , .

: ALternativly, , myDict.Where(x => !x.Key.EndsWith("_comment"))

0

Checked below answer

        Dictionary<string, string> objstr = new Dictionary<string, string>();
        objstr.Add("question1", "7");
        objstr.Add("question1_comment", "pretty difficult");
        objstr.Add("question2", "9");
        objstr.Add("question2_comment", "");
        objstr.Add("question3", "5");
        objstr.Add("question3_comment", "Never on time");

        var Mainobj = objstr.Where(x => x.Key.Contains("_"));
        var obj = objstr.Where(x => x.Key.Contains("_") == false);
        var final = from objl in obj
                    join Mainobjl in Mainobj
                    on objl.Key equals Mainobjl.Key.Replace("_comment", "") into matching
                    select new
                    {
                        question = objl.Key,
                        rank = objl.Value,
                        comment = matching.FirstOrDefault().Value
                    };
        var obj11 = final.ToList();
0
source

You should create some structure to store the values ​​for these questions, i.e.

public struct Question 
{
    public string QuestionId { get; set; }
    public string Answer { get; set; }
    public string Comment { get; set; }
}

and build List<Question >:

var list = dict
    .Where(x => !x.Key.Contains("comment"))
    .Select(x => 
    new Question() 
    {
        QuestionId =x.Key, 
        Answer = x.Value, 
        Comment = dict.Single(y => 
            y.Key == String.Concat(x.Key,"_comment")).Value})
    .ToList();

demo is a little faster than a solution with a list of tables

0
source

Source: https://habr.com/ru/post/1605732/


All Articles