0

I'm trying to purge duplicate value from the list and I'm not sure of a best way to do this.

List<string> sqlOrderBy = new List<string>();

sqlOrderBy.Add("Trim ASC");
sqlOrderBy.Add("Year ASC");
sqlOrderBy.Add("Make DESC");
sqlOrderBy.Add("Year DESC");
sqlOrderBy.Add("Model ASC");
sqlOrderBy.Add("Make ASC");

What I'm trying to figure out is to search for duplicate prefix values like "Year" and "Make" and keep the last one in the list but purge the earlier one regardless of the "ASC" or "DESC" value... What I want it to do is this...

//Trim ASC
//Year DESC
//Model ASC
//Make ASC

Thanks...

4

2 回答 2

2

一种选择是按第一部分对其进行分组,然后取每个组中的最后一个条目:

List<string> query = sqlOrderBy.GroupBy(x => x.Split(' ')[0])
                               .Select(g => g.Last())
                               .ToList();

使用您的示例数据运行它,我得到:

Trim ASC
Year DESC
Make ASC
Model ASC

那是你想要的吗?

编辑:要评论排序,这将不按原始顺序返回元素,而是按指定第一部分的顺序返回。如果您想要原始订单,可以这样做,但有点时髦:

List<string> query = sqlOrderBy.AsEnumerable()
                               .Reverse()
                               .GroupBy(x => x.Split(' ')[0])
                               .Select(g => g.First())
                               .Reverse()
                               .ToList();

(这个AsEnumerable()调用只是为了List<T>.Reverse从等式中删除——我们不是想调用它。)

所以我们从末尾开始分组,这意味着组将以相反的顺序出现,然后我们可以再次反转结果。这给了我们以下结果:

Trim ASC
Year DESC
Model ASC
Make ASC
于 2013-06-14T17:39:38.833 回答
0

使用MoreLINQDistinctBy

sqlOrderBy.AsEnumerable().Reverse().DistinctBy(n => n.Split(' ')[0]);
于 2013-06-14T17:41:13.480 回答