2014-09-24 25 views
0

我有一個IEnumerableLINQ通過IEnumerable的迭代和設置複製到空

IEnumerable<Pets> pets; 

它由

public string Name { get; set; } 
public string Other { get; set; } 
public decimal? Price { get; set; } 

我想通過這個迭代,發現是重複的所有價格和設置這些重複的價格爲空。

說一隻貓和一隻狗有同樣的價格:10.55。我想保留第一個,但刪除所有剩餘的價格。

+2

什麼樣的研究有你試圖找到解決這個問題的辦法嗎?您嘗試過哪些嘗試解決方案,以及您使用這些解決方案遇到了哪些問題? – Servy 2014-09-24 17:37:31

+0

我發現了很多與IEnumerable匹配的需求。感謝您的反對票。 – NoviceDeveloper 2014-09-24 17:44:00

+5

「刪除」和「將價格設置爲空」是兩個不同的東西 - 這是什麼? – 2014-09-24 17:50:32

回答

2

方式:

1)刪除重複(我建議):

var filtered = pets.GroupBy(pet => pet.Price).Select(group => group.First()); 

2)排序& evalute - 設置爲空值來代替重複的,你想(你確定要設置空值而不是像1中那樣去除)?)。

var newPets = pets.OrderBy(per => pet.Price).ToList(); 
if (!newPets.Any()) return newPets; 
var last = 0; 
for (var i = 1; i < newPets.Count; i++) 
{ 
    if (newPets[i].Price == newPets[last].Price) newPets[i] = null; 
    else last = i; 
} 

return newPets; 

我認爲,排序是在這種情況下,充足:O(n * log n) + O(n)O(n^2)定製迭代搜索重複的每個元素。

3)傳統方法(不排序,最慢)

var newPets = pets.ToList(); 
for (var i = 0; i < newPets.Count; i++) 
{ 
    if (newPets[i] == null) continue; 
    var price = newPets[i].Price; 
    for (var j = i + 1; j < newPets.Count; j++) 
    { 
     if (newPets[j].Price == price) newPets[j] = null; 
    } 
} 

由於d士丹利已經注意到(但我已經錯過了它),你可能必須設置Pricenull,而不是整個記錄。然後,簡單地將其更改爲decimal?,然後寫入newPets[i].Price = null;而不是空的整個記錄​​。

+0

作爲第三種變體使用['Distinct'](http://msdn.microsoft.com/en-us/library/bb338049(v = vs.110).aspx) – Grundy 2014-09-24 17:59:36

1

對於初學者來說,decimal不能爲空,所以我會回答它,就好像你有一個decimal?類型,這樣你就能理解這個過程。

Linq針對查詢而不是更新。您可能項目在原有基礎上一個新的集合,而是一個foreach可能更合適:

// list to keep tack of found prices 
var prices = new List<decimal>(); 
foreach(Pet pet in pets) 
{ 
    if(prices.Contains(pet.Price.Value)) 
     // price was found - set this one to null 
     pet.Price = null; 
    else 
     // add to the list of "found" prices 
     prices.Add(pet.Price.Value); 
} 
+0

methinks better'HashSet 'that simply List: - ) – Grundy 2014-09-24 18:04:02

+2

@Grundy的表現?當然。我比對優化代碼更感興趣的是說明這個過程。 – 2014-09-24 18:08:32

1
public class Pet 
{ 
    public string Name { get; set; } 
    public string Other { get; set; } 
    public decimal? Price { get; set; } 
} 

注意,現在的價格是可以爲空(decimal?

return pets 
    .OrderBy(x => x.Name) 
    .GroupBy(x => x.Price) 
    .OrderBy(x => x.Key) 
    .SelectMany(x => (new[] { x.First() }).Union(x.Skip(1).Select(n => new Pet { Name = n.Name, Other = n.Other, Price = null }))) 
    .ToList();