日期:2014-05-18  浏览次数:20966 次

求写一个LINQ GROUPBY

class Model
{
public string col {get;set;}
public string co2 {get;set;}
public string co3 {get;set;}
public string co4 {get;set;}
}


var result = new list<Model>{

new Model { col1 = "1",col2 = "True",col3 = "True",col4 = "True"}
,
new Model { col1 = "2",col2 = "True",col3 = "False",col4 = "True"}
,
new Model { col1 = "2",col2 = "True",col3 = "False",col4 = "False"}
};



对 result 后3列进行group by True算1其余算2 不考虑异常情况 

谢谢了  


分不多 请见谅 

 



------解决方案--------------------
C# code
var result = sourcelist
             .Select(x => new Model() 
                 { 
                    col1 = (x.col2 == "True" && x.col3 == "True" == x.col4 == "True") ? "1" : "2",
                    col2 = x.col2,
                    col3 = x.col3,
                    col4 = x.col4
                 });

------解决方案--------------------
C# code

void Main()
{
    var result = new List<Model>{
        new Model { col1 = "1",col2 = "True",col3 = "True",col4 = "True"},
        new Model { col1 = "2",col2 = "True",col3 = "False",col4 = "True"},
        new Model { col1 = "2",col2 = "True",col3 = "False",col4 = "False"}
        };
    var query=result.GroupBy(r=>new {r.col2,r.col3,r.col4})
                    .Select(g=>new Model{ 
                        col1=g.FirstOrDefault().col1,
                        col2=g.Key.col2=="True"?"1":"2",
                        col3=g.Key.col3=="True"?"1":"2",
                        col4=g.Key.col4=="True"?"1":"2"
                    });
        Console.WriteLine(query);
}

class Model
{
public string col1 {get;set;}
public string col2 {get;set;}
public string col3 {get;set;}
public string col4 {get;set;}
}