Linq groupby IdCordinator only if categery type count greater than one -
need group records idcordinator, conditions
- if category type not equal "s", include in group
- if category type "s" for particular coordinator , count greater than 1 include in group
- if category type "s" a particular coordinator , count equal 1 not include in group
how should frame clause. if have clause below, if there 1 element list though not of category "s" returns 0 records.
using system;
using system.collections.generic; using system.linq;
namespace linqgroupbywhere { class program { static void main( string[] args ) { studentlist studentlist = new studentlist(); studentlist.getlist(); console.readkey(); } }
public class studentlist { public void getlist() { list<students> stdlst = new list<students>(); stdlst.add( new students( "stud1", 20, "m", "i001" ) ); stdlst.add( new students( "stud2", 20, "m", "i001" ) ); stdlst.add( new students( "stud3", 20, "m", "i002" ) ); stdlst.add( new students( "stud4", 20, "m", "i003" ) ); stdlst.add( new students( "stud5", 20, "s", "i001" ) ); stdlst.add( new students( "stud6", 20, "s", "i001" ) ); stdlst.add( new students( "stud7", 20, "s", "i002" ) ); var lst = stdlst.groupby( s => s.idcordinator ) .selectmany( sg => sg.where( s => !s.category.equals( "s" ) || sg.count( c => c.category.equals( "s" ) ) > 1 ) .select( student => student.name ) ) .orderby( o => o ); console.writeline( string.join( ",", (string[]) lst.toarray() ) ); } } public class students { public students( string name, int age, string cat, string sicordinator ) { this.name = name; this.age = age; this.category = cat; this.idcordinator = idcordinator; } public string name { get; set; } public int age { get; set; } public string category { get; set; } public string idcordinator { get; set; } }
}
you can write output want :
var lst = stdlst.groupby(s => s.idcordinator) .selectmany(sg => sg.where(s => !s.category.equals("s") || sg.count(c => c.category.equals("s")) > 1) .select(student => student.name)) .orderby(o => o);
hope solves problem.
update constructor :
public students( string name, int age, string cat, string sicordinator ) { this.name = name; this.age = age; this.category = cat; this.idcordinator = sicordinator; // assiging same field here, making null }
Comments
Post a Comment