我有以下列表:
List<MyClass> problemList = new List<MyClass>;
这个类的结构如下:
public class MyClass
{
public int UserId { get; set; }
public string FullName { get; set; }
public string Role { get; set; }
public List<string> ForumList { get; set; }
public MyClass()
{
ForumList = new List<string>();
}
}
我有另一个作为参数发送的列表:
List<string> fForums = new List<string>;
我需要能够通过我的 ProblemList.ForumList 并删除所有论坛名称 fForums 列表中不。
关闭这个让我开始工作会导致我在循环中修改problemList时出错。 (我的代码可能不起作用,因为我删除了代码,但试图记住它的顶部)
foreach (var i in problemList)
foreach (var n in i.ForumList)
if (!fForums.Contains(n))
i.ForumModList.Remove(n);
有谁知道如何使这项工作? 提前谢谢!
答案 0 :(得分:3)
最明显的途径是创建两个论坛列表的交集并将其分配给属性:
problemList.ForEach(mc => mc.ForumList = mc.ForumList.Intersect(fForums).ToList());
对于以下示例:
List<MyClass> problemList = new List<MyClass>
{
new MyClass {ForumList = new List<string>{"aaa", "bbb", "ccc"}},
new MyClass {ForumList = new List<string>{"aaa", "bbb"}},
new MyClass {ForumList = new List<string>{"xxx", "yyy"}},
};
List<string> fForums = new List<string> {"aaa", "bbb"};
problemList.ForEach(mc => mc.ForumList = mc.ForumList.Intersect(fForums).ToList());
problemList中的项目的ForumList将具有以下值:
1:"aaa","bbb"
2:"aaa","bbb"
3:<empty>
答案 1 :(得分:1)
最简单的方法是每次迭代制作一个新的forumList副本。像这样:
foreach (var i in problemList)
List fList = new ArrayList(i.ForumList);
foreach (var n in fList)
if (!fForums.Contains(n))
i.ForumModList.Remove(n);
这样您就不会编辑迭代的列表,而是编辑它的副本。
答案 2 :(得分:1)
如果我理解你想从problemList的ForumList中删除所有未找到的条目。您可以执行以下操作:
problemList.ForumList.RemoveAll(f => !fForums.Contains(f));
经过测试:
MyClass problemList = new MyClass();
problemList.ForumList.Add("A");
problemList.ForumList.Add("B");
problemList.ForumList.Add("C");
problemList.ForumList.Add("D");
problemList.ForumList.Add("E");
List<string> fForums = new List<string>();
fForums.Add("C");
fForums.Add("D");
problemList.ForumList.RemoveAll(f => !fForums.Contains(f));
problemList.ForumList
还剩下两项,C
和D
。
这是你在找什么?
答案 3 :(得分:0)
我不确定你想要哪个版本,所以我会留下两个版本:
这将从每个problemList
的ForumList中删除,该论坛列表与fForumn中的项目匹配。
foreach (var problemItem in problemList)
{
problemItem.ForumList = problemItem.ForumList
.Except(fForums);
}
在此版本中,您需要查看每个problemList
项。对于该项目,请查看ForumnList
元素中的任何元素是否与fForums
中的项目匹配。如果匹配,请排除problemList
元素。
var filteredList = problemList
.Where(x => !x.ForumList.Intersect(fForums).Any())
.ToList();
Intersect
将返回x.ForumList
和fForums
中的元素。因此,如果Any
匹配,则应将其排除。