Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List.Contains(item) with generic list of objects

Tags:

c#

If you have a List how do you return the item if a specified property or collection of properties exists?

public class Testing
{
    public string value1 { get; set; }
    public string value2 { get; set; }
    public int value3 { get; set; }
}
public class TestingList
{
    public void TestingNewList()
    {
        var testList = new List<Testing>
                           {
                               new Testing {value1 = "Value1 - 1", value2 = "Value2 - 1", value3 = 3},
                               new Testing {value1 = "Value1 - 2", value2 = "Value2 - 2", value3 = 2},
                               new Testing {value1 = "Value1 - 3", value2 = "Value2 - 3", value3 = 3},
                               new Testing {value1 = "Value1 - 4", value2 = "Value2 - 4", value3 = 4},
                               new Testing {value1 = "Value1 - 5", value2 = "Value2 - 5", value3 = 5},
                               new Testing {value1 = "Value1 - 6", value2 = "Value2 - 6", value3 = 6},
                               new Testing {value1 = "Value1 - 7", value2 = "Value2 - 7", value3 = 7}
                           };

        //use testList.Contains to see if value3 = 3
        //use testList.Contains to see if value3 = 2 and value1 = "Value1 - 2"


    }
}
like image 319
Nic Avatar asked Feb 02 '09 16:02

Nic


People also ask

What is generic List in C#?

Generic List<T> is a generic collection in C#. The size can be dynamically increased using List, unlike Arrays.

What does List t mean?

The List<T> is a collection of strongly typed objects that can be accessed by index and having methods for sorting, searching, and modifying list. It is the generic version of the ArrayList that comes under System. Collections. Generic namespace.

What is List in C sharp?

List in C# is a collection of strongly typed objects. These objects can be easily accessed using their respective index. Index calling gives the flexibility to sort, search, and modify lists if required. In simple, List in C# is the generic version of the ArrayList.

How many generic type parameters does the dictionary class have?

Generic. Dictionary<TKey,TValue> generic type has two type parameters, TKey and TValue , that represent the types of its keys and values.


2 Answers

You could use

testList.Exists(x=>x.value3 == 3)
like image 200
Mark Avatar answered Oct 08 '22 00:10

Mark


If you're using .NET 3.5 or better, LINQ is the answer to this one:

testList.Where(t => t.value3 == 3);
testList.Where(t => t.value3 == 2 && t.value1 == "Value1 - 2");

If not using .NET 3.5 then you can just loop through and pick out the ones you want.

like image 31
CubanX Avatar answered Oct 08 '22 01:10

CubanX