我有一个c#解决方案,根据字符串列名列表从datatable中过滤列,然后将数据作为字典对象列表返回。我想知道这个解决方案是否是最优的,或者是否有更简单和更好的方法。
我有一个webapi,它根据用户ID返回用户个人资料数据。 web api将包含_include querystring参数,该参数包含我们需要验证和返回数据的属性名称。例:
http://localhost/SomeApi/UserProfile/100?_include=IsDeleteAllowed,IsMigrated
。
web api应返回包含属性值的数据。 IsDeleteAllowed = 1
[HttpGet, ActionName("ById"), RouteSupport(IncludeObjects = new string[] { "All Properties" })]
public override List<Dictionary<string, string>> Read(int id)
{
try
{
Controller userController = new Controller(ConnString);
DataTable dt = userController.GetUserProfileByUser(id);
// GetIncludes() method return the list of _include columns requested by the user that
// needs to be filtered out from the dataset that has all the user profile properties
List<string> inc = this.Request.GetIncludes();
// Filters the columns based on the requested user profile properties (_include)
var data = dt.AsDataView().ToTable(true, inc.ToArray<string>());
// Convert the data into list of dictionary object
var results = data
.AsEnumerable()
.Select(dr => data.Columns.Cast<DataColumn>()
.ToDictionary(dc => dc.ColumnName, dc => dr[dc].ToString()))
.ToList();
return results;
}
catch (Exception ex)
{
throw new Exception("User Read(int id) Failed", ex);
}
}
在代码userController.GetUserProfileByUser(id)
中,按用户ID返回所有用户配置文件属性和数据库中的值。
以下代码行
var data = dt.AsDataView().ToTable(true, inc.ToArray<string>())
过滤数据表以仅返回请求的列(用户配置文件)。
然后,.Select(dr => dt.Columns.Cast<DataColumn>().ToDictionary(dc => dc.ColumnName, dc => dr[dc])).ToList()
尝试将结果转换为要返回给用户的字典对象列表。
我得到的结果(如果,xml):
<ArrayOfArrayOfKeyValueOfstringstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<ArrayOfKeyValueOfstringstring>
<KeyValueOfstringstring>
<Key>IsDeleted</Key>
<Value>1</Value>
</KeyValueOfstringstring>
<KeyValueOfstringstring>
<Key>IsMigrated</Key>
<Value>0</Value>
</KeyValueOfstringstring>
</ArrayOfKeyValueOfstringstring>
</ArrayOfArrayOfKeyValueOfstringstring>