c# - Select Distinct rows using Linq -


the data follow

id title        category           link        categoryid 1  matrix   sci-fi   text goes here  http://...  1  2  simpsons cartoon  text goes here  http://...  2 3  avengers     action   text goes here  http://...  3 4  matrix   sci-fi   text goes here  http://...  1 5  1      sci-fi   text goes here  http://...  1 6  hobbit   sci-fi   text goes here  http://...  1 

i have checkbox list containing categories. problem if user selects 'action' , 'sci-fi' category display matrix displayed twice.

this try getting unique rows in sql query.

select distinct title, about, link mytable inner join tablecategories on categoryid = tablecategoriesid group title, about, link 

using linq,

(from table in movietables join x in categoryidlist on categoryid equals x slect table).distinct() 

note categories in separate table linked categoryid. need displaying unique or distinct rows in linq.

you can happily select result list of whatever want:

var v = entry in tables         matching_logic_here         select new {id = some_id, val=some_value}; 

and can run distinct on list (well, tolist() on above make one), based on needs.

the following should illustrate mean (just paste linqpad. if you're using vs, rid of .dump():

void main() {     var input  = new list<mock_entry> {         new mock_entry {id = 1, name="the matrix", cat= "sci-fi"},         new mock_entry {id = 2, name="the simpsons" ,cat= "cartoon"},         new mock_entry {id = 3, name="avengers" ,cat= "action"},         new mock_entry {id = 4, name="the matrix", cat= "sci-fi"},         new mock_entry {id = 5, name="the one" ,cat= "sci-fi"},         new mock_entry {id = 6, name="the hobbit",cat= "sci-fi"},     };      var v = input.where(e=>e.cat == "action" || e.cat =="sci-fi")                 .dump()                 .select(e => new {n = e.name, c =e.cat})                 .dump()     ;      var d = v.distinct()             .dump()     ; }  // define other methods , classes here public struct mock_entry {     public int id {get;set;}     public string name {get;set;}     public string cat {get;set;} } 

another option use distinctby more linq suggested in this question

edit:

even simpler, can use groupby, , select first entry (you'll lose id though, you).
here's example work above:

var v = input.groupby (i => i.name)    .select(e => e.first ())    .dump()    .where(e=>e.cat == "action" || e.cat =="sci-fi")    .dump() ;     

will yield:

1 matrix sci-fi
3 avengers action
5 1 sci-fi
6 hobbit sci-fi


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -