2011-06-13 16 views
25

असल में, मैं इसे कैसे बना सकता हूं ताकि मैं कुछ ऐसा कर सकूं: CurrentCollection.Contains(...), यह तुलना करके कि आइटम की संपत्ति पहले से ही संग्रह में है या नहीं?संग्रह में आइटम जोड़ें यदि संग्रह में आइटम की संपत्ति की तुलना करके पहले से ही इसमें शामिल नहीं है?

public class Foo 
{ 
    public Int32 bar; 
} 


ICollection<Foo> CurrentCollection; 
ICollection<Foo> DownloadedItems; 

//LINQ: Add any downloaded items where the bar Foo.bar is not already in the collection? 

उत्तर

34

आप खोज जो तत्वों संग्रह में पहले से ही नहीं कर रहे हैं से शुरू:

var newItems = DownloadedItems.Where(x => !CurrentCollection.Any(y => x.bar == y.bar)); 

और फिर बस उन्हें जोड़ें:

foreach(var item in newItems) 
{ 
    CurrentCollection.Add(item); 
} 

नोट पहला ऑपरेशन है, तो आकार द्विघात जटिलता हो सकता है DownloadedItemsCurrentCollection के आकार के करीब है। कि समस्याओं के कारण समाप्त होता है (पहले मापने!), आप एक HashSet उपयोग कर सकते हैं रैखिक करने के लिए नीचे लाने के लिए जटिलता:

// collect all existing values of the property bar 
var existingValues = new HashSet<Foo>(from x in CurrentCollection select x.bar); 
// pick items that have a property bar that doesn't exist yet 
var newItems = DownloadedItems.Where(x => !existingValues.Contains(x.bar)); 
// Add them 
foreach(var item in newItems) 
{ 
    CurrentCollection.Add(item); 
} 
3

आप Any विधि कॉल और संग्रह में वस्तु के प्रकार के जो भी संपत्ति के लिए तुलना करने के लिए एक मूल्य के पारित कर सकते हैं

if (!CurrentCollection.Any(f => f.bar == someValue)) 
{ 
    // add item 
} 

एक और अधिक पूर्ण समाधान हो सकता है:

DownloadedItems.Where(d => !CurrentCollection.Any(c => c.bar == d.bar)).ToList() 
    .ForEach(f => CurrentCollection.Add(f)); 
0
var newItems = DownloadedItems.Where(i => !CurrentCollection.Any(c => c.Attr == i.Attr)); 
0

आप इसे ऐसा कर सकते हैं:

CurrentCollection.Any(x => x.bar == yourGivenValue) 
8

R.Martinho फर्नांडीस पद्धति का उपयोग करना और 1 लाइन को बदलने:

CurrentCollection.AddRange(DownloadedItems.Where(x => !CurrentCollection.Any(y => y.bar== x.bar))); 
1

या All

CurrentCollection 
    .AddRange(DownloadedItems.Where(x => CurrentCollection.All(y => y.bar != x.bar))); 
1

का उपयोग कर आप Enumerable.Except उपयोग कर सकते हैं:

यह दो सूचियों की तुलना करेगा और केवल उन तत्वों को लौटाएगा जो केवल पहली सूची में दिखाई देते हैं।

CurrentCollection.AddRange(DownloadedItems.Except(CurrentCollection)); 
संबंधित मुद्दे