I have an interface for items which are Votable: (Like StackExchange, Reddit, etc...)
// Irrelevant properties left out (Creator, Upvotes, Downvotes, etc)
internal interface IVotable
{
double HotScore { get; set; }
double VoteTotal { get; set; }
DateTime CreatedDate { get; set; }
}
I have a concrete base class which extends this interface and defines a constructor to populate the default properties:
internal class SCO : IVotable
{
public double HotScore { get; set; }
public double VoteTotal { get; set; }
public DateTime CreatedDate { get; set; }
public SCO(SPListItem item, List<Vote> votes)
{
VoteTotal = UpVotes - DownVotes;
HotScore = Calculation.HotScore(Convert.ToInt32(UpVotes), Convert.ToInt32(DownVotes), Convert.ToDateTime(item["Created"]));
CreatedDate = Convert.ToDateTime(item["Created"]);
}
Here is an example of a class in use which extends this base class and it's constructor:
class Post : SCO
{
public string Summary { get; set; }
public Uri Link { get; set; }
public Post(SPListItem item, List<Vote> votes)
: base(item, votes)
{
Summary = (string) item["Summary"];
Link = new UriBuilder((string) item["Link"]).Uri;
}
}
Over 90% of the time, I'm returning sorted collections of the classes for rendering on a page.
I would like to have a generic method of some kind that takes in a collection of DataBase Items, a List of Votes to match with the Items, creates a List, and then sorts that list based on a passed ENUM that defines how to sort.
I've tried a few approaches, many of them based on previous posts. I'm not sure if I'm approaching this in the right way. While the solutions do work, I see a lot of Boxing, or Reflection, or some kind of (possibly major) sacrifice in performance for readability, or ease of use.
What is the best way to Create a Sorted List of objects that can be used in any subsequent child class as long as that class extends the base class?
Previous Approach that is working:
Create a List of <T> from a base class
A Generic List of <T>
embedded in the Base Class which extends Activator.CreateInstance
using reflection to return the list:
public static List<T> SortedCollection<T>(SPListItemCollection items, ListSortType sortType, List<Vote> votes) where T : SCO
Request for Sample of use:
static public List<Post> Get100MostRecentPosts(ListSortType sortType)
{
var targetList = CoreLists.SystemAccount.Posts();
var query = new SPQuery
{
Query = "<OrderBy><FieldRef Name=\"Created\" Ascending=\"False\" /></OrderBy>",
RowLimit = 100
};
var listItems = targetList.GetItems(query);
var votes = GetVotesForPosts(listItems);
return Post.SortedCollection<Post>(listItems, sortType, votes);
}