ili*_*ica 108 c# contains list
public class PricePublicModel
{
public PricePublicModel() { }
public int PriceGroupID { get; set; }
public double Size { get; set; }
public double Size2 { get; set; }
public int[] PrintType { get; set; }
public double[] Price { get; set; }
}
List<PricePublicModel> pricePublicList = new List<PricePublicModel>();
Run Code Online (Sandbox Code Playgroud)
如何检查元素是否pricePublicList
包含特定值.更确切地说,我想检查是否存在pricePublicModel.Size == 200
?另外,如果这个元素存在,如何知道它是哪一个?
编辑如果字典更适合这个,那么我可以使用字典,但我需要知道如何:)
Ant*_*ram 178
如果您有一个列表,并且想要知道列表中存在哪个元素与给定条件匹配,则可以使用FindIndex
实例方法.如
int index = list.FindIndex(f => f.Bar == 17);
Run Code Online (Sandbox Code Playgroud)
f => f.Bar == 17
具有匹配标准的谓词在哪里.
在你的情况下,你可能会写
int index = pricePublicList.FindIndex(item => item.Size == 200);
if (index >= 0)
{
// element exists, do what you need
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*ite 117
bool contains = pricePublicList.Any(p => p.Size == 200);
Run Code Online (Sandbox Code Playgroud)
Tia*_*ago 26
你可以使用exists
if (pricePublicList.Exists(x => x.Size == 200))
{
//code
}
Run Code Online (Sandbox Code Playgroud)
Jac*_*cob 13
使用LINQ这很容易做到:
var match = pricePublicList.FirstOrDefault(p => p.Size == 200);
if (match == null)
{
// Element doesn't exist
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 10
你实际上并不需要LINQ,因为List<T>
它提供了一个完全符合你想要的方法:Find
.
搜索与指定谓词定义的条件匹配的元素,并返回整个内容中的第一个匹配项
List<T>
.
示例代码:
PricePublicModel result = pricePublicList.Find(x => x.Size == 200);
Run Code Online (Sandbox Code Playgroud)
var item = pricePublicList.FirstOrDefault(x => x.Size == 200);
if (item != null) {
// There exists one with size 200 and is stored in item now
}
else {
// There is no PricePublicModel with size 200
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
232050 次 |
最近记录: |