C#如何找到从列表中的最后一项有使用 linq 的同一项目

标签: Linq C#
发布时间: 2017/2/27 4:19:04
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

上课记录

public class Record
{
    public string recordID { get; set; }

    public string recordName { get; set; }
}


列表记录包括许多记录,他们可能就等于

List<Record> records = new List<Record>();

records.Add(new Record { recordID = "1", recordName = "name1" });
records.Add(new Record { recordID = "2", recordName = "name2" });
records.Add(new Record { recordID = "3", recordName = "name3" });
records.Add(new Record { recordID = "4", recordName = "name4" });
records.Add(new Record { recordID = "1", recordName = "name1" });
records.Add(new Record { recordID = "2", recordName = "name2" });
records.Add(new Record { recordID = "3", recordName = "name3" });

从该列表中

我想要搜索从 recordID 哪里相同的列表中的最后一项

做些什么

示例︰ 查找从最后一个相同的项目列表,然后涂上颜色

records.All(p =>{
    (p.recordID == 3 /*any recordID*/ 
    && /*the record of the same is the last in list*/
    ? "<span style='corlor:red'>" + p.recordName + "</span>"
    : "<span style='corlor:green'>" + p.recordName + "</span>");
    return true;
});

谢谢你

解决方法 1:

public class SOProblem1
{
    public static void Main()
    {
        var records = new List<Record>
        {
            new Record {recordID = "1", recordName = "name1"},
            new Record {recordID = "2", recordName = "name2"},
            new Record {recordID = "3", recordName = "name3"},
            new Record {recordID = "4", recordName = "name4"},
            new Record {recordID = "1", recordName = "name1"},
            new Record {recordID = "2", recordName = "name2"},
            new Record {recordID = "3", recordName = "name3"}
        };

        var t = records.GroupBy(x => x.recordID);

        foreach (var record in t)
        {
            Console.WriteLine(record.Last().recordName);
        }

        Console.ReadKey();
    }
}

public class Record
{
    public string recordID { get; set; }

    public string recordName { get; set; }
}
官方微信
官方QQ群
31647020