Linq循环比较值列表框.净c#

本文关键字:列表 循环 比较 Linq | 更新日期: 2023-09-27 18:10:48

我试图通过避免多次foreach循环来完成此任务来压缩我的代码。我有一个由表a填充的列表框,我需要将这些值与表B进行比较,以填充另一个列表。

表A与表B有1对多的关系,虽然我的解决方案暂时有效,但它使用了相当多的内存,所以我需要压缩它。

List<int> listProj = new List<int>();
var _tableB = from t in TableB
              where t.StatID == 1 || t.StatID == 2
              select p.ID;
var _tableA = from ListItem n in lstTableA.Items
              where _tableB.Contains(int.Parse(n.Value)) && n.Selected == true
              select n;
foreach (ListItem i in _tableA)
{
    int affID = Convert.ToInt32(i.Value);
    if (TableB.Where(t => t.ID == affID && t.StatID == 1 || t.StatID == 2).Any()
    {
        foreach(var item in TableB.Where(t => t.ID == affID && t.StatID == 1 || t.StatID == 2)
        {
            int pID = Convert.ToInt32(item.pID);
            listProject.Add(projID);
        }
    }
}

主要问题是这两个循环遍历了相当多的记录,这会导致内存泄漏。我觉得有一种方法可以一次抓取许多记录并将它们添加到列表中,因此表a和表b之间的一对多关系

Linq循环比较值列表框.净c#

除非我在你的程序逻辑上犯了一个错误,否则我认为这将给你与上面的整个代码相同的结果。

返回项目id:

List<int> listProj = (from t in TableB
                        where (from n in lstTableA.Items.Cast<ListItem>().ToList()
                            where n.Selected == true
                            select n).Any(g => int.Parse(g.Value) == t.ID)
                            && (t.StatID == 1 || t.StatID == 2)
                        select t.pID).ToList();