user1765862
user1765862

Reputation: 14155

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

Upvotes: 0

Views: 104

Answers (3)

Vivek Nuna
Vivek Nuna

Reputation: 1

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)));

Upvotes: 0

khaled saleh
khaled saleh

Reputation: 518

try this (if total of items is 60, 25 for isHome and 40 for isBreaking) then:

var posts = repository.GetAll(); //65 items   
int HomePagePostsPercentage = (int) (posts.Where(x => x.IsHomePage == true).Count() / posts.Count()) * 100; //val = 25
int pctBreakingNewsCount = (int) (posts.Where(x => x.IsBreakingNews == true).Count() / posts.Count()) * 100; //val = 40
var listWithPctHomePagePosts = posts.Take(posts.Count() / 25);

if you want just to filter out items with IsHomePage is true, then just do:

var HomePagePostsItesm = posts.Where(x => x.IsHomePage == true).ToList();

Upvotes: 1

Mario Vernari
Mario Vernari

Reputation: 7304

Probably because you want to refer to the Count method exposed by Linq:

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

Upvotes: 1

Related Questions