如何返回List<>包含列表中的最新项目<>与LINQ

时间:2018-06-07 11:18:17

标签: c# linq tuples

我有以下元组列表:

var allXmlUsers = new List<(string login, string email, string createdOn)>();
allXmlUsers.Add(("thompson", "sdfsd@dkfjdkf.com", "2015-03-04 20:32:04"));
allXmlUsers.Add(("dupont", "asdfdfd@dkfjdkf.com", "2017-03-04 20:32:04"));
allXmlUsers.Add(("james", "dfsdfs33@dkfjdkf.com", "2016-03-04 20:32:04"));

我想用仅包含最新项目的List<>替换它,例如&#34;杜邦公司&#34;

我可以返回一个这样的元组对象:

var single = (from x in allXmlUsers orderby x.createdOn descending select x).FirstOrDefault();

然后我返回一个List<>,重新排序如下:

var list = from x in allXmlUsers orderby x.createdOn descending select x;

但是如何返回仅包含一个元组的List<>,即最新的元组?

//allXmlUsers = ((from x in allXmlUsers orderby x.createdOn descending select x).FirstOrDefault()).ToList();
//(error: cannot resolve symbol to List)

2 个答案:

答案 0 :(得分:7)

您可以使用Take方法仅从可枚举

中获取1个元素
var single = (from x in allXmlUsers orderby x.createdOn descending select x)
             .Take(1)
             .ToList();

修改

上面的代码段将返回一个空列表(长度为0的列表),这可能是所需的行为,但您可能还希望返回包含单个null值的列表。如果是这样,您可以使用DefaultIfEmpty方法

var single = (from x in allXmlUsers orderby x.createdOn descending select x)
             .Take(1)
             .DefaultIfEmpty()
             .ToList();

答案 1 :(得分:0)

如果这是您经常使用的操作,那么另一个选项是创建ToSingletonList扩展方法,如下所示:

public static class Extensions
{  
     /// <summary>
     /// Returns the first element of the sequence in a list or a default value in a list if the sequence contains no elements.
     /// </summary>
     /// <param name="source">The IEnumerable<T> to return the first element of.</param>
     /// <returns>default in a list if source is empty; otherwise, the first element in source in a list.</returns>

    public static List<T> ToSingletonList<T>(this IEnumerable<T> source) => 
               new List<T> { source.FirstOrDefault() };
}

然后在你的情况下你做:

var single = (from x in allXmlUsers orderby x.createdOn descending select x).ToSingletonList();