我有一个词典==&gt; Dictionary<int, cwObject>
样式在cwObject值中具有不同的属性,我想将它与属性列表进行比较,并创建一个新的字典,其中删除等于列表的值。
Dictionary<int, cwObject> styles = stylesOT.Objects;
List<string> elementToRemove.
答案 0 :(得分:0)
你的问题不完整,但我通过编写示例尝试了最好的镜头,试试这个:
//example of class cwObject
public class cwObject{
public string stringtocompare;
public object anyotherobject;
}
//main process
static void Main(string[] args)
{
//List contains string to remove
List<string> stringtoremove = new List<string>();
stringtoremove.Add("stringtoremove");
//dummy data for cwObject
cwObject cw = new cwObject();
cw.stringtocompare = "stringok";
cw.anyotherobject = "anything";
cwObject cw1 = new cwObject();
cw1.stringtocompare = "stringtoremove";
cw.anyotherobject = 100;
//dummy data for dictionary to compare
Dictionary<int, cwObject> dictcw = new Dictionary<int, cwObject>();
dictcw.Add(0,cw);
dictcw.Add(1,cw1);
//new dictionary for container of results
Dictionary<int,cwObject> filtereddict = new Dictionary<int,cwObject>();
cwObject cwtemp = null;
//start enumerating
foreach (string str in stringtoremove)
{
foreach (KeyValuePair<int, cwObject> entry in dictcw)
{
cwtemp = entry.Value;
if (!cwtemp.stringtocompare.Equals(str)) {
filtereddict.Add(entry.Key,entry.Value);
}
}
}
//output the result
foreach (KeyValuePair<int, cwObject> entry in filtereddict)
{
cwtemp = entry.Value;
Console.WriteLine(cwtemp.stringtocompare);
}
Console.ReadLine();
}
答案 1 :(得分:0)
您可以从列表中创建一个哈希集以进行快速查找(或从头开始使其成为哈希集),然后您可以从词典中过滤项目并从中创建新词典。
对于此示例,我假设cwObject
有一个名为element
的字符串属性,您可以将其与列表中的字符串进行比较:
HashSet<string> remove = new HashSet<string>(elementToRemove);
Dictionary<int, cwObject> remaining =
styles.Where(o => !remove.Contains(o.Value.element))
.ToDictionary(o => o.Key, o => o.Value);