简体   繁体   English

在 C# 中将字典转换为匿名对象?

[英]Convert Dictionary to anonymous object in c#?

I have a web API I'm building in C#.我有一个用 C# 构建的 Web API。 This web API is used as a front end to query a SQL database.此 Web API 用作查询 SQL 数据库的前端。 I am using SqlKata as the engine to perform the querying.我使用 SqlKata 作为引擎来执行查询。 When generating a WHERE clause, the SqlKata documentation states the following:生成 WHERE 子句时,SqlKata 文档说明如下:

Multiple fields多个字段

If you want to filter your query against multiple fields, pass an object that represents col/values.如果要针对多个字段过滤查询,请传递一个表示列/值的对象。

var query = new Query("Posts").Where(new {
    Year = 2017 ,
    CategoryId = 198 ,
    IsPublished = true,
});

I want to be able to avoid hardcoding the WHERE clause, but rather base it on passed in querystrings.我希望能够避免对 WHERE 子句进行硬编码,而是基于传入的查询字符串。 My idea was to add each querystring name and value to a Dictionary then somehow use the values of that Dictionary within the SqlKata .Where() clause.我的想法是将每个查询字符串名称和值添加到字典中,然后以某种方式在 SqlKata .Where() 子句中使用该字典的值。 I thought maybe I could convert the Dictionary to the required anonymous object, but I can't get it to work.我想也许我可以将 Dictionary 转换为所需的匿名对象,但我无法让它工作。 Any ideas folks on how to do this?关于如何做到这一点的任何想法? So my url might be:所以我的网址可能是:

https://webapi.com.au/api?store=120&name=james https://webapi.com.au/api?store=120&name=james

Dictionary: store=120 name=james字典:store=120 name=james

Query: var query = new query("Posts").Where(anonObject)查询:var query = new query("Posts").Where(anonObject)

( anonObject would be {store=120,name=james} ) ( anonObject 将是 {store=120,name=james} )

You don't need an anonymous object.您不需要匿名对象。 Looking at the SqlKata docs, you can just build up the query by looping over the dictionary, something like this:查看 SqlKata 文档,您可以通过遍历字典来构建查询,如下所示:

//Assuming the dictionary is something like Dictionary<string, object>

var query = new Query("Posts");

foreach(var element in dictionary)
{
    query = query.Where(element.Key, element.Value);
}

var result = query.Get();

Note: Never even heard of SqlKata before so this is just from looking at the docs.注意:以前从未听说过 SqlKata,所以这只是查看文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM