我已尝试过以下代码,但无法理解。
Dictionary<string, BO.User> lstuserCH = new Dictionary<string, BO.User>();
foreach (DataRow row1 in _data.wsm_PurchaseOrder_Auth) {
if (((Convert.ToInt32(row1("AuthLevel")) == 1)
&& !row1.IsNull("Authorised"))) {
// here i need only the 1st element of dictonary lstuserCH
}
else
{
//dictionary lstuserCH should be remain as it is.
}
}
答案 0 :(得分:1)
您可以采取几个不同的角度。
首先,您可以编写一个接收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
这种方法的最大优势是什么?它不假设结果数据表中行的顺序 - 硬编码行[0],行[1],行[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获取数据的方式,这样就可以在一行中获取数据。 / p>
无论如何,希望有所帮助! : - )
*****编辑,根据OP的评论:*****
正如一些人所提到的,Dictionary对象 NOT 可靠地排序。这不是你应该依赖的东西。 (见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);
如果这没有意义,可以使用Google搜索C#List Take&#39; C#IEnumerable ToList&#39;等等。
答案 1 :(得分:0)
您可以选择个人行并执行以下业务逻辑:
public void ValidateFirstThreeRows(DataTable dt)
{
if (dt.Rows.Count < 3)
{
// Handle this case
}
var row1 = dt.Rows[0];
var row2 = dt.Rows[1];
var row3 = dt.Rows[2];
if ((int)row1["AuthLevel"] == 1
&& bool.TryParse(row1["Authorized"]?.ToString(), out bool result)
&& (int)row2["AuthLevel"] == 2
&& bool.TryParse(row2["Authorized"]?.ToString(), out result)
&& (int)row3["AuthLevel"] == 3
&& bool.TryParse(row3["Authorized"]?.ToString(), out result))
{
// Do your stuff
}
}