嵌套的foreach循环只返回distinct



我有一个数据库,每个电子邮件地址都应该属于一个唯一的客户,但我有很多重复的地址。我使用了一个sql查询来列出客户ID,即每个事件的电子邮件地址对,其中有多个客户ID映射到一个电子邮件地址。结果看起来像这样(更改地址以保护无辜者)

Customer ID   Email
101233        bob@myaddress.com
108993        bob@myaddress.com
113224        bob@myaddress.com
89223         mary@otherdomain.com
188223        mary@otherdomain.com

在c#中,我将其填充到一个名为dt的数据表中,该表有722行。我用这个来制作第二个名为distinctTbl的DataTable,其中344行只包含不同的电子邮件地址,使用这个:

DataTable distinctTbl = dt.AsDataView().ToTable(true, "Email");

我正在尝试使用嵌套循环为每个电子邮件地址制作一个整数列表(客户ID):

foreach (DataRow dr in distinctTbl.Rows)
{
    // for each email address:
    List<int> idNums = new List<int>();
    foreach (DataRow myRow in dt.Rows) 
    {
        // for every customerID / email pair in the original table
        if (myRow["Email"] == dr["Email"])
        {
            idNums.Add((int)myRow["CustomerID"]);
        }
    }
    // Do something with the List<int> before exiting outside loop
}

当我运行此代码时,每个整数列表只包含一个值。该值是正确的,但每个电子邮件地址至少应该有两个。我已经做了足够的调试,发现它总是正确地识别第一个,但跳过任何后续的匹配。我肯定我错过了一些显而易见的东西,但有人看到发生了什么吗?

放弃foreach循环

您可以使用Linq更容易地获取您要查找的信息。

Dictionary<string, List<int>> emailIDs =
    dt.Rows.OfType<DataRow>()
           .GroupBy(row => (string)row["Email"])
           .ToDictionary(grp => grp.Key,
                         grp => grp.Select(row => (int)row["CustomerID"]).ToList());

一个快速简单的解决方案是使用Dictionary<string,List<int>>而不是列表:

    Dictionary<string, List<int>> idNums = new Dictionary<string, List<int>>();
    foreach (DataRow myRow in dt.Rows)
    {
        string email = myRow["Email"].ToString()
        if (idNums.ContainsKey(email))
        {
            idNums[email].Add((int)myRow["CustomerID"]);
        }
        else
        {
            idNums.Add(email, new List<int> { (int)myRow["CustomerID"] });
        }
    }

现在idNums将包含与每个电子邮件相关联的id列表。

最新更新