首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

求写一个LINQ GROUPBY,该怎么处理

2012-03-19 
求写一个LINQ GROUPBYclass Model{public string col {getset}public string co2 {getset}public stri

求写一个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;}} 

热点排行