组在Linq中使用Select语句

时间:2013-08-08 02:56:39

标签: c# sql linq c#-4.0

var query = from i in SFC.Supplies_ReceiveTrans 
            orderby i.Poprctnm descending 
            select new { RR = i.Poprctnm };

结果:

RR-01,
RR-01, 
RR-02, 
RR-02, 
RR-02, 
RR-TEST, 
RR-TEST,

我如何在这种陈述中对RR进行分组

结果:

RR-01,
RR-02, 
RR-TEST

只是进行一些修改,询问是否有可能做到这一点或你的想法?很抱歉要求太多,真的有兴趣了解更多关于linq ..如何将其转换为字符串,因为它显示真或假..布尔语句

var query = SFC.Supplies_ReceiveTrans.Select(s =>
s.Poprctnm.StartsWith(p))
.Distinct()
.OrderBy(p => p)
.Select(p => new { RR = p })
.Take(10);

4 个答案:

答案 0 :(得分:2)

在这种情况下,您可以使用DistinctGroupBy方法

var query = SFC.Supplies_ReceiveTrans.Select(s=> s.Poprctnm)
            .Distinct()
            .OrderByDescending(p => p)
            .Select(p=> new { RR = p });  

如果您使用OrderByDescending,则结果将为

RR-TEST 
RR-02 
RR-01 

但我认为你想要OrderBy,那么结果将是

RR-01 
RR-02 
RR-TEST 

请尝试以下

var query = SFC.Supplies_ReceiveTrans.Select(s=> s.Poprctnm)
            .Distinct()
            .OrderBy(p => p)
            .Select(p=> new { RR = p }); 

答案 1 :(得分:1)

var query = SFC.Supplies_ReceiveTrans
            .GroupBy(x=>x.Poprctnm)
            .Select(g=>g.First())
            .OrderByDescending(x=>x.Poprctnm)
            .Select(x=>new { RR = x.Poprctnm });

如果您想将result作为群组:

var query = SFC.Supplies_ReceiveTrans
            .GroupBy(x=>x.Poprctnm)
            .OrderByDescending(g=>g.Key);                

答案 2 :(得分:1)

var result = SFC.Supplies_ReceiveTrans
                     .Select(x => new { RR = x.Poprctnm })
                     .Distinct()
                     .OrderByDescending(x => x.Poprctnm);

答案 3 :(得分:0)

您好像需要Distinct,而不是群组

var query = SFC.Supplies_ReceiveTrans
               .Select(x => new {RR = i.Poprctnm})
               .Distinct()
               .OrderByDescending(i => i);