我有一个包含评估答案的字典,如下所示:
{
{"question1", "7"},
{"question1_comment", "pretty difficult"},
{"question2", "9"},
{"question2_comment", ""},
{"question3", "5"},
{"question3_comment", "Never on time"},
}
但是我需要将分数项和注释项组合成一个对象,如下所示
{
{"question1", "7", "pretty difficult"},
{"question2", "9", ""},
{"question3", "5", "Never on time"},
}
我想我需要使用Aggregate方法来完成这个任务,但是我不知道从哪里开始。
发布于 2015-09-03 20:34:26
你可以这样做:
var res = data
.Keys
.Where(s => !s.EndsWith("_comment"))
.Select(s => new[] {s, data[s], data[s+"_comment"]})
.ToList();
ides首先过滤掉所有不以"_comment"
结尾的键,然后使用这些键在结果数组中查找两段内容。
发布于 2015-09-03 20:33:22
未经测试,但也许是个好主意:
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$
的所有条目(意味着所有条目都以一个数字结尾)。对于这些条目,您可以创建一个匿名类型的新实例,在该实例中,通过在字典中搜索适当的项来检索注释。
编辑:或者,为了避免使用正则表达式,您可以首先使用
myDict.Where(x => !x.Key.EndsWith("_comment"))
发布于 2015-09-03 20:37:21
在答案下面勾选
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();
https://stackoverflow.com/questions/32375424
复制相似问题