这里有几个你可以采取的不同角度。
首先,您可以编写一个函数,该函数接受一个 DataTable 并返回它是否拥有某个授权级别:
bool AuthorizedForLevel(DataTable recordsForPONumber, int authLevel)
{
foreach(DataRow dr in recordsForPONumber.Rows)
{
if (dr.Field<int>("AuthLevel") == authLevel)
{
int? authorized = dr.Field<int?>("Authorized");
if (!authorized.HasValue) return false;
if (authorized.Value == 0) return false;
return true;
}
}
return false; // didn't have an entry, so they must not be authorized.
}
...然后,您的逻辑很简单:
if (AuthorizedForLevel(resultDT, 1))
if (!AuthorizedForLevel(resultDT, 2))
if (!AuthorizedForLevel(resultDT, 3))
// what you want to do
这种方法的最大优势是什么?它不假设结果数据表中行的顺序 - 硬编码 row[0]、row[1]、row[2] 的缺点是假设所有行都存在并且以特定顺序存在。此外,它很好并且经过重构,因此逻辑非常清晰简洁。
第二种方法是在 SQL 端很好地格式化数据。我的意思是,您没有理由必须从 C# 跨多行进行解码。
-- some variable @poNum that's passed to your stored procedure
select
(select Authorized from myTable where PONumber = @poNum and AuthLevel = 1) as AuthorizedFor1,
(select Authorized from myTable where PONumber = @poNum and AuthLevel = 2) as AuthorizedFor2,
(select Authorized from myTable where PONumber = @poNum and AuthLevel = 3) as AuthorizedFor3
... 也就是,不要取回三行并尝试在 C# 端解析它,只需更改从 SQL 获取数据的方式,以便在单行中取回数据。
无论如何,希望对您有所帮助! :-)
***** 编辑,基于 OP 的 cmets:*****
正如一些人所提到的,Dictionary 对象是不可靠排序的。这不是你应该依赖的东西。 (见Does the Enumerator of a Dictionary<TKey, TValue> return key value pairs in the order they were added?)
简短的故事:如果您继续使用 Dictionary 对象,那么当订单没有像您期望的那样返回时,您将被烧毁。
但这没关系 - 你可以转移到其他东西。两个不错的选择是:
List<Tuple<string, BO.User>> versionA;
List<KeyValuePair<string, BO.User>> versionB;
好的,既然我已经摆脱了那么大的谨慎?您可以使用一些不错的方便的 Linq 函数来获取您要查找的内容:
List<Tuple<string, BO.user>> listICareAbout;
if (someCondition)
listICareAbout = myMainList.Take(1).ToList();
else
listICareAbout = new List<Tuple<string, BO.user>>(myMainList);
如果这没有意义,请在谷歌上搜索“C# List Take”、“C# IEnumerable ToList”等。