如何在linq查询中获取唯一值

时间:2017-03-26 16:24:31

标签: c# entity-framework linq

我想获得最新的10个唯一记录,其最后12个字符应该是唯一的。  样本数据

json数据

[{ “时间戳”: “2017-03-20T05:27:01.688Z”, “数据帧”: “ACnrAAAAAAAAAAA =”, “FCNT”:165, “端口”:3 “RSSI”: - 85, “SNR”:7, “sf_used”:12, “ID”:1489987621688, “解密”:真},{ “时间戳”: “2017-03-20T05:27:41.675Z”, “数据帧”:“ACntAAAAAAAAAAA = ”, “FCNT”:169, “端口”:3 “RSSI”: - 85, “SNR”:9 “sf_used”:12, “ID”:1489987661675, “解密”:真} ...

AGMDAQo1/wSsCPU=
AGMEAQo1/wSsCPU=
AGMFAQo1/wSsCPU=
AGMGAQo1/wSsCPU=
AGMHAQo1/wSsCPU=
ASHAAQo2FgSsBxc=

获得这样的输出,但它应该只有一个,因为最后12个字符是相同的。

AGMDAQo1/wSsCPU=,
AGMEAQo1/wSsCPU=,
AGMFAQo1/wSsCPU=

期望的输出

AGMDAQo1/wSsCPU=
ASHAAQo2FgSsBxc=

 var Pirs = Newtonsoft.Json.JsonConvert.DeserializeObject<List<AssetDetail>>(responseString);
                    var items = Pirs.Where(a => !a.dataFrame.EndsWith("AAAAAAAAAAA="))
                                             .GroupBy(a => a.dataFrame)
                                             .Select(g => g.First())
                                             .OrderByDescending(a => a.timestamp)
                                             .Take(10);

模型

 public class AssetDetail
        {
            public long id { get; set; }
            public DateTime timestamp { get; set; }
            public string dataFrame { get; set; }
            public long fcnt { get; set; }
            public int port { get; set; }
            public int rssi { get; set; }
            public string snr { get; set; }
            public string sf_used { get; set; }
            public bool decrypted { get; set; }
        }

2 个答案:

答案 0 :(得分:1)

使用Distinct()

Newtonsoft.Json.JsonConvert.DeserializeObject<List<AssetDetail>>(responseString);
                    var items = Pirs.Where(a => !a.dataFrame.EndsWith("AAAAAAAAAAA="))
                                             .GroupBy(a => a.dataFrame)
                                             .Select(g => g.First())
                                             .Distinct()
                                             .OrderByDescending(a => a.timestamp)
                                             .Take(10);

希望它有所帮助!

答案 1 :(得分:1)

您可以在GroupBy函数中使用a.dataFrame.Substring(a.dataFrame.Length - 12)按照其dataFrame属性末尾具有相同12个字符的AssetDetails进行分组。

var Pirs = Newtonsoft.Json.JsonConvert.DeserializeObject<List<AssetDetail>>(responseString);
var items = Pirs.Where(a => !a.dataFrame.EndsWith("AAAAAAAAAAA="))
                                 .GroupBy(a => a.dataFrame.Substring(a.dataFrame.Length - 12))
                                 .Select(g => g.First())
                                 .OrderByDescending(a => a.timestamp)
                                 .Take(10);

如果使用GroupBy()

,则无需使用Distinct()函数