有没有办法将以下内容映射到Dictionary<int,int>
?它似乎产生了返回结果的行数,但它们没有值......
Sql sql = new Sql()
.Append("SELECT Count(*) as 'Answer Count', QuestionId")
.Append("FROM CF.Answers")
.Append("WHERE SurveyId = @0", surveyId)
.Append("GROUP BY QuestionId");
var result = database.Fetch<Dictionary<int,int>>(sql);
Run Code Online (Sandbox Code Playgroud)
Rob*_*nik 15
List<T>
Fetch<T>()
方法返回a 的事实List<T>
意味着在您的代码示例中它返回
List<Dictionary<int, int>> result = ...
Run Code Online (Sandbox Code Playgroud)
这可能不是你想要的,每个字典只会举行一个项目,这就是你想要首先拥有字典的全部原因.据我了解你的问题,你真的想得到:
Dictionary<int, int> result = ...
Run Code Online (Sandbox Code Playgroud)
当然有扩展方法List<T>
,您可以将其转换为其他类型.一种这样的方法是.ToDictionary()
可以将结果转换为您想要获得的字典.
现在我们手头有这里的问题是,我们可以使用什么类型与Fetch
方法?最初我想到了两件事:
KeyValuePair<int, int>
Tuple<int, int>
Run Code Online (Sandbox Code Playgroud)
即使好的想法,它们都不会起作用,因为Key
属性中KeyValuePair
没有公共setter而第二个没有PetaPoco可以使用的无参数构造函数.
我们在这里留下的是创建一个类似Tuple
但具有我们可以与PetaPoco实际使用的功能的自定义类型.让我们将此类型设为通用类型,以便我们可以轻松地将其重用于不同类型:
public class Pair<T1, T2>
{
public T1 Item1 { get; set; }
public T2 Item2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
使用这个自定义类,我们现在可以轻松获取字典:
Sql sql = new Sql()
.Append("SELECT QuestionId as Item1, COUNT(*) as Item2")
.Append("FROM Answers")
.Append("WHERE SurveyId = @0", surveyId)
.Append("GROUP BY QuestionId");
var result = database
.Fetch<Pair<int,int>>(sql)
.ToDictionary(i => i.Item1, i => i.Item2);
Run Code Online (Sandbox Code Playgroud)
请注意,我已经颠倒了选择字段的顺序(并设置了不同的别名),因为您不希望计数是字典键(因为它们可能重复),而是问题ID.所以它要么像我一样颠倒选择字段的顺序,要么为.ToDictionary()
扩展方法提供正确的选择器.