如何根据列表中的元素向列表添加值 [英] How to add values to a list based on the the element present in list
本文介绍了如何根据列表中的元素向列表添加值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个清单
I have a list
Selected objSelectd;// Selected is a class
List<Selected> objlistSelected = new List<Selected>();
objSelectd.Image = ImageName;
objSelectd.strText = ImageHeading;
objlistSelected.Add(objSelectd);
如果列表objlistSelected包含ImageName,那么我需要添加安装价值
if the list objlistSelected contains ImageName then i need to add Installation value
objSelectd.Installation = "aaaa"
i试过这些并且它不起作用
i have tried these and its not working
objSelectd.Installation = "AAA"
if (objlistSelected.Contains(ImageName))
{
objlistSelected.Add(objSelectd);
}
for (int i = 0; i < objlistSelected.Length; i++)
{
if (objlistSelected[i].Contains(myString)) // (you use the word "contains". either equals or indexof might be appropriate)
{
return i;
}
}
请帮助
先谢谢
Please help
Thanks in Advance
推荐答案
您需要通过列表中对象的字段进行检查。你不能使用contains,因为它会查找整个对象。
You need to check by a field of the objects in the list. You can't use contains as it will look for the whole object.
if(objlistSelected.Any(x =>x.Image==ImageName))
{
...
}
[更新]
如果你想更新元素,试试这个:
[Update]
If you want to update the element, try this:
var element = objlistSelected.FirstOrDefault(x =>x.Image==ImageName);
if(element != null)
{
element.Installation = "AAA";
}
See following LinqPad[^] snippet:
class C { public string A {get;set;} public string B {get;set;} };
void Main()
{
var L = new List<C>() {new C() { A="A1", B="B1"}, new C() { A="A2", B="B2"}};
L.Dump();
var X = L.FirstOrDefault(x => x.A == "A2");
if (X!=null)
{
X.B = "BBBBB";
}
L.Dump();
}
您可以考虑实施词典
或KeyValuePair
然后您可以通过密钥直接访问该元素,然后更新它。图像名称可以作为键,值将是安装值。
You can think about implementing aDictionary
orKeyValuePair
where you can then access the element directly by key and then update it. The image name can act as a key and value will be the installation value.
这篇关于如何根据列表中的元素向列表添加值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文