[英]Add linq property selector to Expression
我在Linq中具有以下表達式:
public static IEnumerable<T> NextDistinct<T>(this IEnumerable<T> items)
{
T previous = default(T);
bool first = true;
foreach(T item in items)
{
if (first || !Equals(previous, item))
{
first = false;
previous = item;
yield return item;
}
}
}
我需要添加一個選擇器,如下所示:
.NextDistinct(i => i.articlepricehistory_sell)
我嘗試過,但是鍵選擇無法正常工作:
public static IEnumerable<TSource> NextDistinct<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
{
TSource previous = default(TSource);
bool first = true;
foreach (TSource item in source)
{
if (first || !Equals(previous, item))
{
first = false;
previous = item;
yield return item;
}
}
}
更新:
這是我的查詢,我只需要使用articlepricehistory_sell列做一個不同的查詢
var ArticlesSellHistory = dt.AsEnumerable()
select new
{
articlepricehistory_sell = articlespricehistory.Field<Double>("articlepricehistory_sell"),
articlepricehistory_date = articlespricehistory.Field<DateTime>("articlepricehistory_date")
})
.NextDistinct(i => i.articlepricehistory_sell)
.ToList();
結果:
365 05/09/2015 02:30:31 p.m.
370 11/10/2015 04:19:37 p.m.
369.59 11/10/2015 04:19:54 p.m.
365 11/10/2015 04:20:05 p.m.
365 11/10/2015 04:20:58 p.m.
365 11/10/2015 04:33:22 p.m.
預期結果:
365 05/09/2015 02:30:31 p.m.
370 11/10/2015 04:19:37 p.m.
369.59 11/10/2015 04:19:54 p.m.
365 11/10/2015 04:20:05 p.m.
您所需TSource previous
就是用TKey previousKey
替換TSource previous
並將其與當前項目鍵(均使用傳遞的選擇器提取)進行比較。 也可以允許為兩個函數指定一個比較器。 有問題的功能可能是這樣的
public static IEnumerable<TSource> NextDistinct<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
IEqualityComparer<TKey> keyComparer = null)
{
if (source == null) throw new ArgumentNullException("source");
if (keySelector == null) throw new ArgumentNullException("keySelector");
if (keyComparer == null) keyComparer = EqualityComparer<TKey>.Default;
var previousKey = default(TKey);
bool first = true;
foreach (TSource item in source)
{
var itemKey = keySelector(item);
if (first || !keyComparer.Equals(previousKey, itemKey))
{
yield return item;
first = false;
previousKey = itemKey;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.