你可以這樣做之前你排序。識別重複的最簡單方法是使用GroupBy
。
由於您使用的匿名類型,你可以通過自己的項目組:
var data =
new[] {
new { A = 3, B = 3 },
new { A = 2, B = 2 },
new { A = 2, B = 2 },
new { A = 1, B = 1 }
};
var groups = data.GroupBy(x => x); // works since we are using anonymous types that use value equality
if(groups.Any(g => g.Count() > 1)
{
// throw exception
}
var result = groups.Select(g=>g.Key)
.OrderBy(x => x.A)
.ThenBy(x => x.B)
.ToList();
如果您使用的不是現實中的匿名類型則只是要用來定義屬性組「平等」。
您還可以檢查連續重複的「內聯」使用擴展方法:
public static IEnumerable<T> ThrowIfConsecutiveItemsAreEqual<T>(this IEnumerable<T> source)
{
bool isFirst = true;
T prev = default(T);
foreach(var item in source)
{
if(!isFirst && item.Equals(prev))
throw new Exception(); // TODO: use a better exception type and message
yield return item;
isFirst = false;
prev = item;
}
}
調用擴展方法ToList
之前避免多個枚舉:
var query =
new[] {
new { A = 3, B = 3 },
new { A = 2, B = 2 },
new { A = 2, B = 2 },
new { A = 1, B = 1 }
}
.OrderBy(x => x.A)
.ThenBy(x => x.B)
.ThrowIfConsecutiveItemsAreEqual()
.ToList();
也許在不同的地方打電話? –
對不起,我已經在我的問題中澄清了這一點:我正在尋找一些與LINQ一起玩的東西,即不需要再次迭代數據。 – Simeon