Reputation: 1358
Alright, so I have the following method:
private List<Store> NextPrevious(List<Store> model, int numFields, int page, ref bool nextRef, ref bool previousRef)
{
if (model.Count > numFields && page == 0)
{
model = model.Skip(page * (numFields - 1)).Take(numFields - 1).ToList();
next = true;
previous = false;
}
else if (page > 0 && model.Skip(page + (numFields - 2)).Count() <= (numFields - 1))
{
model = model.Skip(page + (numFields - 2)).Take(numFields - 1).ToList();
next = false;
previous = true;
}
else if (page > 0 && model.Count > (page + 1))
{
model = model.Skip(page + (numFields - 2)).Take(numFields - 2).ToList();
next = true;
previous = true;
}
return model.ToList();
}
I'd call the method like this:
model.Groups = NextPrevious(model.Groups.ToList<Store>(), 3, groupPage, ref next, ref previous);
model.Groups
is of type List<Group>
. Group
is a child class of a class Store
. Now, is there a way to reference the group when I'm sending it in the method (ref
), or at least return it, like I tried, unsuccessfully, and make it work. Right now if I type this and try to run it, I get an error:
Cannot implicitly convert type 'System.Collections.Generic.List<(path)Store> to 'System.Collections.Generic.List<(path)Group>'
I know what the error means, but I just don't have the knowledge to go around it, so I'm asking here for help. By the way, I can't cast it as return model.ToList<Group>()
neither, since the method is created so it could be used for other class objects that inherit the Store
class.
Thanks!
Upvotes: 2
Views: 75
Reputation: 39366
A solution could be changing the NextPrevious
as a generic method and declaring the following constraint on the type parameter:
private List<T> NextPrevious<T>(List<T> model, int numFields, int page, ref bool nextRef, ref bool previousRef) where T:Store
{
//...
}
This way you just need to do this:
model.Groups = NextPrevious(model.Groups, 3, groupPage, ref next, ref previous);//call model.Groups.ToList() in case the Groups property is not a List<Group>
You can omit the type argument at the time you call the NextPrevious<T>
method because the compiler will infer it based on the first method argument you pass.
Upvotes: 1
Reputation: 15445
Well, one way you could do this is use Cast()
, something like:
model.Groups = NextPrevious(...).Cast<Group>().ToList();
This will blow up at runtime with an InvalidCastException
if any of the objects returned from NextPrevious
can't be casted to a Group
, but...
You could also within NextPrevious()
cast before you return,
....
return model.Cast<Group>.ToList();
Upvotes: 1