how to check if List element contains an item with a Particular Property Value

前端 未结 6 871
野的像风
野的像风 2020-12-07 11:54
public class PricePublicModel
{
    public PricePublicModel() { }

    public int PriceGroupID { get; set; }
    public double Size { get; set; }
    public double S         


        
相关标签:
6条回答
  • 2020-12-07 12:27
    bool contains = pricePublicList.Any(p => p.Size == 200);
    
    0 讨论(0)
  • 2020-12-07 12:31

    This is pretty easy to do using LINQ:

    var match = pricePublicList.FirstOrDefault(p => p.Size == 200);
    if (match == null)
    {
        // Element doesn't exist
    }
    
    0 讨论(0)
  • 2020-12-07 12:34

    If you have a list and you want to know where within the list an element exists that matches a given criteria, you can use the FindIndex instance method. Such as

    int index = list.FindIndex(f => f.Bar == 17);
    

    Where f => f.Bar == 17 is a predicate with the matching criteria.

    In your case you might write

    int index = pricePublicList.FindIndex(item => item.Size == 200);
    if (index >= 0) 
    {
        // element exists, do what you need
    }
    
    0 讨论(0)
  • 2020-12-07 12:37
    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
    }
    
    0 讨论(0)
  • 2020-12-07 12:38

    You don't actually need LINQ for this because List<T> provides a method that does exactly what you want: Find.

    Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire List<T>.

    Example code:

    PricePublicModel result = pricePublicList.Find(x => x.Size == 200);
    
    0 讨论(0)
  • 2020-12-07 12:40

    You can using the exists

    if (pricePublicList.Exists(x => x.Size == 200))
    {
       //code
    }
    
    0 讨论(0)
提交回复
热议问题