【问题标题】:How to compare two list and add all list to new list ASP.Net MVC 4 using linq如何使用 linq 比较两个列表并将所有列表添加到新列表 ASP.Net MVC 4
【发布时间】:2016-07-14 02:22:35
【问题描述】:

我有两个列表
列表 A

List<test> populate = new List<test>();
{
  populate.Add(new test(){ID = 1, name="AAA", nameID=1, type=1, isSelected=false});
  populate.Add(new test(){ID = 2, name="BBB", nameID=2, type=1, isSelected=false});
  populate.Add(new test(){ID = 3, name="CCC", nameID=3, type=1, isSelected=false});
}

列表 B

    List<build> populateBuild = new List<build>();
{
  populateBuild.Add(new test(){ID = 1, name="AAA", nameID=1, type=1, isSelected=false});
  populateBuild.Add(new test(){ID = 3, name="CCC", nameID=3, type=1, isSelected=false});
}

我想要实现的是:
1) 我想要新列表,(列表 C)

2)在List C中,我想要List A中的所有数据,但是List A中的isSelected的值>,当与List B中的数据进行比较时,将变为TRUE

3) 表示如果列表B存在于列表A中,则列表A中的isSelected的值将变为TRUE并添加到列表 C

4) 如果列表B不存在在列表A中,它仍然会被添加到列表C,但不改变isSelected值(保持false)。

谢谢,

【问题讨论】:

    标签: list asp.net-mvc-4 razor arraylist list-comparison


    【解决方案1】:

    我假设您的意思是List&lt;test&gt; populateBuild = new List&lt;test&gt;();(不是List&lt;build&gt;)。您可以使用

    生成第三个列表
    // Get the ID's of the 2nd list
    IEnumerable<int> populateBuildIds = populateBuild.Select(x => x.ID);
    // Initialize the 3rd list
    List<test> listC = new List<test>();
    // Copy all elements from the first list and update the isSelected property
    foreach (test t in populate)
    {
        listC.Add(new test()
        {
            ID = t.ID, 
            name = t.name, 
            nameID = t.nameID, 
            type = t.type, 
            isSelected = populateBuildIds.Contains(t.ID) // true if also in 2nd list
        });
    }
    

    【讨论】:

    • 只是为了确认一下,您的意思是如果 id 也在第二个列表中意味着 isSelected 会自动更改为 true?
    • 是的,没错(如果它不在第二个列表中,它将是false
    • 代码运行顺利,但我不知道 isSelected 是否更改为 true。我想在我的剃须刀中将 listC 显示为复选框。因此,当我显示它时,它会显示列表中的所有数据,并带有未选中的复选框(表示为 false)。因为 isSelected 更改为 true,意味着复选框也应该被选中?
    • 抱歉,不确定您的意思。如果视图是 listC(IEnumerable) and your using a for` 循环生成视图的模型,则第 1 项和第 3 项将被选中,第 2 项将被取消选中(我可以创建一个快速的 DotNetFiddle if您不理解)。如果复选框未显示正确的“已检查”状态,则表示您查看错误
    • 参考this DotNetFiddle。注意我稍后会删除它,所以如果你想保留它,你需要分叉它
    【解决方案2】:

    Adiciona esta classe no seu projeto:

       public static class LINQToObjectExtensions
        {
            public static void UpdateAll<T>(this IEnumerable<T> source, Action<T> action)
            {
                foreach (var item in source)
                    action(item);
            }
        }
    

    depois executa desta maneira:

    ListC.UpdateAll(p => p.isSelected = ListB.Contains(p));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-06
      • 2021-10-03
      • 1970-01-01
      • 2014-10-22
      • 2014-05-16
      相关资源
      最近更新 更多