apomene
apomene

Reputation: 14389

Generic List and corresponding method

sI am pretty noob in generic Lists and would really use some help. (Don't even know if generic is the apropriate use for my cause).

I have :

 public class GenericList<T> : IList<T>
    {          
        public DateTime date { get; set; }
        public int state { get; set; }            
    }

All I want is to create a method that will take as an argument the state of T and will return its firstIndex.

I guess it is pretty simple but as I mentioned no experience with so ever

Upvotes: 2

Views: 84

Answers (3)

Redwan
Redwan

Reputation: 758

As I understand you want to use some of T properties/methods inside your class. To do this you can set an interface requirement to T.

interface IMyInterface{
    int GetState();
}

public class GenericList<T> : List<T> where T: IMyInterface 
{          
    public DateTime date { get; set; }
    public int GetState(int i){return this[i].GetState(); }
}

Like this. But elements of your list will have to implement IMyInterface.

Upvotes: 2

Kenneth
Kenneth

Reputation: 28737

If you want to search the list for an index you don't need to create a specific subclass of IList<T>, you can use the built-in methods for that. Here's an example:

public class SomeClass
{
    public int State {get; set;}
    public DateTime Date{get; set;}
}

public void somemethod()
{
    var list = new List<SomeClass>();
    list.Add(new SomeClass{State = 5});

    // Get all the items with state 5
    var itemsWithStateFive = list.Where(item => item.State == 5); 

    // Find the first index of an item that has state 5
    var indexOfStateFive = list.FindIndex(item => item.State == 5); 
}

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460028

I think that you don't need your class GenericList at all since there is already a generic List<T>. Maybe you want to create a class State:

public class State
{
     public DateTime date { get; set; }
     public int state { get; set; }       
}

So you want to find the index of the first with a given state, you can use List.FindIndex:

var allStates = new List<State>();
// fill ...
int index = allStates.FindIndex(s => s.state == givenState);

If you don't have a list(but an array or another kind of IEnumerable<State>) you could still get the index with LINQ:

int index = allStates.Select((s, index) => new { s, index })
    .Where(x => x.s.state == givenState)
    .Select(x => x.index)
    .DefaultIfEmpty(-1)
    .First();

Upvotes: 3

Related Questions