Searching If Value Exists in a List of Objects Using Linq

Searching if value exists in a list of objects using Linq

LINQ defines an extension method that is perfect for solving this exact problem:

using System.Linq;
...
bool has = list.Any(cus => cus.FirstName == "John");

make sure you reference System.Core.dll, that's where LINQ lives.

Check if object with specific value exists in List

You can use Any(),

Any() from Linq, finds whether any element in list satisfies given
condition or not, If satisfies then return true

if(ListA.Any(a => a.Id == stringID))
{
//Your logic goes here;

}

MSDN : Enumerable.Any Method

C# Linq Check if INT exists in list of objects

Your code is converting the memberships into a list of bool, and then seeing if there are any members - which there are as you have a list like: [false, false, false]. What you want is this:

bool x = p1.meberships.Any(a => a.id == correct);

how to check if object already exists in a list

It depends on the needs of the specific situation. For example, the dictionary approach would be quite good assuming:

  1. The list is relatively stable (not a lot of inserts/deletions, which dictionaries are not optimized for)
  2. The list is quite large (otherwise the overhead of the dictionary is pointless).

If the above are not true for your situation, just use the method Any():

Item wonderIfItsPresent = ...
bool containsItem = myList.Any(item => item.UniqueProperty == wonderIfItsPresent.UniqueProperty);

This will enumerate through the list until it finds a match, or until it reaches the end.

Linq check if all values exists in list

Except + Any do what you want:

bool allExist = !new[] { 1, 2, 3 }.Except(OfferPrioritie.Select(x => x.TypeId)).Any();

LINQ query to find objects in list with equal values for one of their properties

GroupBy might be a better option here - a bit more memory but much lower complexity.

eventList.GroupBy(x => x.EventDateTime).Where(g => g.Count() > 1)

Each group's key is the collision datetime, and value is the events which collide on that time.

Adding .Select(g => g.Key) will give you just the datetimes.

LINQ Query: Determining if object in one list exists in another based on key

http://introducinglinq.com/blogs/marcorusso/archive/2008/01/14/the-not-in-clause-in-linq-to-sql.aspx

Consider this code that returns all the customers who don't have an order in the Orders table. This is one SQL query that returns that value.

SELECT *
FROM [dbo].[Customers] AS [t0]
WHERE [t0].[CustomerID] NOT IN (
SELECT [t1].[CustomerID]
FROM [dbo].[Orders] AS [t1]
)

This is not the faster way to get the desired result (using a NOT EXISTS is the favorite way - more on this shortly). LINQ offers a Contains extension method that allows writing the following code.

NorthwindDataContext dc = new NorthwindDataContext();
dc.Log = Console.Out;
var query =
from c in dc.Customers
where !(from o in dc.Orders
select o.CustomerID)
.Contains(c.CustomerID)
select c;
foreach (var c in query) Console.WriteLine( c );

In LINQ to SQL the query is translated into this SQL code:

SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName],
[t0].[ContactTitle], [t0].[Address], [t0].[City],
[t0].[Region], [t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax]
FROM [dbo].[Customers] AS [t0]
WHERE NOT (EXISTS(
SELECT NULL AS [EMPTY]
FROM [dbo].[Orders] AS [t1]
WHERE [t1].[CustomerID] = [t0].[CustomerID]
))

This approach is not only semantically equivalent, but also faster in execution. The following is the result with SET STATISTICS IO ON. The first result is for the hand-written query that use the NOT IN clause. The second result is for the LINQ to SQL generated query.

C# Checking if list of objects contains an object with specific variable

countries.Any(c=>c.Name==name) will return you a Boolean true if name exists in the list, but you might be better swapping Any for FirstOrDefault and testing the result:

var country = countries.FirstOrDefault(c=>c.Name==name);
if(country == default)
//add
else
//update the properties of the `country` variable here

LINQ query to find if items in a list are contained in another list

var test2NotInTest1 = test2.Where(t2 => test1.Count(t1 => t2.Contains(t1))==0);

Faster version as per Tim's suggestion:

var test2NotInTest1 = test2.Where(t2 => !test1.Any(t1 => t2.Contains(t1)));

Looking to query a list of objects based on a property and value in list

You were close, use .Any instead of .Find for the Codes when filtering:

var absenceType = AbsenceCodesList
// first find a valid top level item
.FirstOrDefault(c =>
// is specific company
c.Company == companyCode
// has the target paycode
&& c.Codes.Any(x => x.PayCode == ppc.PayCode))

// then select the desired value
?.Codes.First(c => c.PayCode == ppc.PayCode)
.AbsenceType;


Related Topics



Leave a reply



Submit