Search code examples
c#linqmath.net-core

getting percentage amount of data from a list


I have Post mode

public class Post{
    public bool IsHomePage {get;set;}
    public bool IsBreakingNews {get;set;}
    public bool Title {get;set;}
    ...
}

The idea is to get a certain amount (percentage amount) of posts using type (IsHomePage, IsBreakingNews, ....)

I'm retrieveing data

var posts = repository.GetAll();

int pctHomePagePosts = 25; //%
int pctBreakingNews = 40;  //%

var listWithPctHomePagePosts = posts.Take(posts.Count / 25);

operator / cannot be applied to operands of type method group or int


Solution

  • You need to do like this.

    To get 25%

    var listWithPctHomePagePosts = posts.Take((decimal)(posts.Count() * (pctHomePagePosts / 100)));
    

    To get 40%

    var listWithPctBreakingNews = posts.Take((decimal)(posts.Count() * (pctBreakingNews / 100)));