我正在尝试创建一个比较2个数组结果的函数。如果它们匹配,那么就不需要做任何事情。如果它们不匹配,则需要对SQL表进行更新(称为Products_Extension)。
数组A旨在从用户上载的.csv文件中为每个产品配置文件包含逗号分隔的ItemsAssignedIDs列表(此字段在Products_Extension表中称为uidProducts)。数组B旨在包含数据库中每个产品概要文件的逗号分隔的ItemsAssignedID列表。两个列表都通过ProfileID字段附加到产品配置文件。 (我猜我需要清除数组B中的项目是A和B不匹配,用数组A中的项填充数组B,然后相应地更新数据库)
我有两个函数,一个为数据库中的每个Product Profile构建ItemsAssignedID列表,另一个从上传的.csv文件中获取所有ItemsAssignedID。但我很困惑如何组合它们,以便我可以比较两个阵列。
为每个产品配置文件构建以逗号分隔的ItemsAssignedIDs列表的函数:
private string BuildItemsAssignedList(int ProfileID)
{
string assignedIdList = "";
string sqlQuery = "SELECT [uidProducts] FROM Products_Extension WHERE uidProductProfile = @ProfileID";
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
SqlCommand cmd = new SqlCommand(sqlQuery, cn);
cmd.Parameters.Add(new SqlParameter("@ProfileID", ProfileID));
cmd.CommandType = CommandType.Text;
cn.Open();
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
if (!String.IsNullOrEmpty(assignedIdList))
assignedIdList += ", ";
assignedIdList += (reader["uidProducts"].ToString());
}
reader.Close();
}
cn.Close();
}
return assignedIdList = string.Join(",", assignedIdList);
}
将每个产品配置文件中以逗号分隔的ItemsAssignedIDs列表与.csv文件分开的功能:
private void SaveAssignedItems(int ProfileID, string[] row)
{
string AssignedID = GetValue(row, (int)ProfileColumns.ItemsAssignedIDs);
AssignedID = AssignedID.ToLower();
AssignedID.Trim();
if (AssignedID != "")
{
string[] assignedids = AssignedID.Split(',');
foreach (string item in assignedids)
{
int MyVal = Convert.ToInt32(item);
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Products_Extension SET uidProductProfile = @ProfileID WHERE uidProducts=@AssignedID";
cmd.Parameters.AddWithValue("@ProfileID", ProfileID);
cmd.Parameters.AddWithValue("@AssignedID", item);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
}
}
答案 0 :(得分:0)
据我所知,您希望compare
两个arrays
并在匹配/不匹配时执行某些操作?
请尝试以下方法:
方法1
bool found= false;
int[] a = new int[] { 8, 1, 2, 3, 4 };
int[] b = new int[] { 5, 6, 7, 8 };
foreach (var numberA in a)
{
foreach (var numberB in b)
{
if (numberA == numberB)
{
found= true;
}
}
if(!found)
{
//numberA not found in array B
}
}
Mehtod 2:
int[] a = new int[] { 1, 2, 3, 4 };
int[] b = new int[] { 1, 2, 3 };
var result = a.Except(b).ToArray();
foreach (var item in result)
{
Response.Write("\nItems not in B are :"+item);
}
注意:请不要使用'原样'。相应地做出改变..!