Determine if a sequence contains all elements of another sequence using Linq
Count? How about Not Any?
bool contained = !subset.Except(superset).Any();
In C#, how can i determine if a list has any item from another list?
You're looking to see if the "Intersection" of the lists is non-empty:
if(list.Intersect(list2).Any())
DoStuff();
LINQ: Determine if two sequences contains exactly the same elements
If you want to treat the arrays as "sets" and ignore order and duplicate items, you can use HashSet<T>.SetEquals
method:
var isEqual = new HashSet<int>(first).SetEquals(second);
Otherwise, your best bet is probably sorting both sequences in the same way and using SequenceEqual
to compare them.
Check if one IEnumerable contains all elements of another IEnumerable
There is no "fast way" to do this unless you track and maintain some state that determines whether all values in one collection are contained in another. If you only have IEnumerable<T>
to work against, I would use Intersect
.
var allOfList1IsInList2 = list1.Intersect(list2).Count() == list1.Count();
The performance of this should be very reasonable, since Intersect()
will enumerate over each list just once. Also, the second call to Count()
will be optimal if the underlying type is an ICollection<T>
rather than just an IEnumerable<T>
.
Check if enumeration contains multiple elements without throwing exception?
One approach to see if the sequence has more than one element is to use Take
and Count
, like this:
if (mySequence.Take(2).Count() == 2) {
... // Sequence has at least two elements
}
Take(2)
limits counting to at most two, so using Count()
is not as expensive as in mySequence.Count() > 1
.
If you need to grab the first element, store the result of Take
in a list to avoid iterating the sequence again.
Determine sequence contains no element using LINQ
Try
var d = lst1.Where(q => q <= DateTime.Now).DefaultIfEmpty().Max();
Your result will now contain DateTime.MinValue
if there are no matches
Related Topics
Using the Iterator Variable of Foreach Loop in a Lambda Expression - Why Fails
How to Get the Assembly File Version
The Type or Namespace Name Does Not Exist in the Namespace 'System.Web.Mvc'
Performance Difference for Control Structures 'For' and 'Foreach' in C#
How to Get Client Date and Time in ASP.NET
There Is No Argument Given That Corresponds to the Required Formal Parameter - .Net Error
Task Parallel Library Replacement for Backgroundworker
Detect Antivirus on Windows Using C#
Replace Multiple String Elements in C#
Hyphenated HTML Attributes with ASP.NET MVC
Why Should I Use Ihttpactionresult Instead of Httpresponsemessage
Redirect from Action Filter Attribute
How to Do Template Specialization in C#
What Does "Datetime" Mean in C#
Transparency for Windows Forms Textbox