Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

list

contains

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>(); 

How to check if element of pricePublicList contains certain value. To be more precise, I want to check if there exists pricePublicModel.Size == 200? Also, if this element exists, how to know which one it is?

EDIT If Dictionary is more suitable for this then I could use Dictionary, but I would need to know how :)

like image 456
ilija veselica Avatar asked Feb 08 '11 18:02

ilija veselica


People also ask

How do you check whether a list contains a specified element?

Contains(T) Method is used to check whether an element is in the List<T> or not. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot.

How do you check if a list of object contains a value in C#?

You can use the Enumerable. Where extension method: var matches = myList. Where(p => p.Name == nameToExtract);

How do you check if a list contains a string in C#?

if (myList. Contains(myString)) string element = myList. ElementAt(myList. IndexOf(myString));


1 Answers

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 } 
like image 151
Anthony Pegram Avatar answered Oct 23 '22 22:10

Anthony Pegram