Find an item in a list by LINQ
If you want the index of the element, this will do it:
int index = list.Select((item, i) => new { Item = item, Index = i })
.First(x => x.Item == search).Index;
// or
var tagged = list.Select((item, i) => new { Item = item, Index = i });
int index = (from pair in tagged
where pair.Item == search
select pair.Index).First();
You can't get rid of the lambda in the first pass.
Note that this will throw if the item doesn't exist. This solves the problem by resorting to nullable ints:
var tagged = list.Select((item, i) => new { Item = item, Index = (int?)i });
int? index = (from pair in tagged
where pair.Item == search
select pair.Index).FirstOrDefault();
If you want the item:
// Throws if not found
var item = list.First(item => item == search);
// or
var item = (from item in list
where item == search
select item).First();
// Null if not found
var item = list.FirstOrDefault(item => item == search);
// or
var item = (from item in list
where item == search
select item).FirstOrDefault();
If you want to count the number of items that match:
int count = list.Count(item => item == search);
// or
int count = (from item in list
where item == search
select item).Count();
If you want all the items that match:
var items = list.Where(item => item == search);
// or
var items = from item in list
where item == search
select item;
And don't forget to check the list for null
in any of these cases.
Or use (list ?? Enumerable.Empty<string>())
instead of list
.
How can I find object in List with Linq?
If you are trying to find an object in collectionMyObject
which has item with id 2, then this should work:
MyObject myObject = collectionMyObject.FirstOrDefault(o => o.Items != null && o.Items.Any(io => io.Id == 2));
And if you are try to find an inner item with id 2, then this query with SelectMany
might be helpful:
MyObject myObject1 = collectionMyObject.Where(o => o.Items != null).SelectMany(o => o.Items).FirstOrDefault(io => io.Id == 2);
linq - find item in list within multiple lists
Couldn't get it working with linq, but works with query syntax.
var leagueMatch = (from teamLeague in community.TeamLeagues
from season in teamLeague.Seasons
from division in season.Divisions
from match in division.Matches.Where(x => x.Id == "1234")
select match).FirstOrDefault();
LINQ query to find items in a list containing substring elements from a second list
We can use EndsWith()
with Path.GetFileNameWithoutExtension()
, as strings in the secondList are not entire file names.
var result = firstList
.Where(path => secondList.Any(fileName => Path.GetFileNameWithoutExtension(path).EndsWith(fileName)));
Try Online
C# Linq Find value inside list of objects inside a list of objects
You should replace the Where
method with Any
mostly, because Where
returns filtered sequence, when Any
determines whether any element of a sequence satisfies a condition
var result = listProducts.Any(product =>
product.title == "ERDSIC" && product.listProperties.Any(property =>
property.title == "size" && property.listValues.Any(v => v.val == 1001)));
However, it's better to wrap this code into method, like extension one, and call with different arguments
public static class Ext
{
public static bool HasTitleAndSize(this IEnumerable<Product> products, string title, int size)
{
return products.Any(product =>
product.title == title && product.listProperties.Any(property =>
property.title == "size" && property.listValues.Any(v => v.val == size)));
}
}
And call in the following way
var result = listProducts.HasTitleAndSize("ERDSIC", 1001); //returns true
result = listProducts.HasTitleAndSize("ERDCON", 1001); //returns false
Linq select objects in list where exists IN (A,B,C)
Your status-codes are also a collection, so use Contains
:
var allowedStatus = new[]{ "A", "B", "C" };
var filteredOrders = orders.Order.Where(o => allowedStatus.Contains(o.StatusCode));
or in query syntax:
var filteredOrders = from order in orders.Order
where allowedStatus.Contains(order.StatusCode)
select order;
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)));
Using LINQ to get a list of items where the item contains a part of an item from another list
var filteredList = models
.Where(x => filterer.Any(y => x.Contains(y))
.ToList();
Distinct
serves no purpose here, as the Where
call doesn't introduce duplicates (unless of course models
has duplicate values, and you want to remove those duplicates).
Use LINQ to get items in one List , that are in another List
var result = peopleList2.Where(p => peopleList1.Any(p2 => p2.ID == p.ID));
Related Topics
Intersection of Multiple Lists with Ienumerable.Intersect()
Change Wpf Controls from a Non-Main Thread Using Dispatcher.Invoke
How to Pass Command-Line Arguments to a Winforms Application
Make First Letter of a String Upper Case (With Maximum Performance)
Default Visibility for C# Classes and Members (Fields, Methods, etc.)
Where to Learn About VS Debugger 'Magic Names'
Do Try/Catch Blocks Hurt Performance When Exceptions Are Not Thrown
Make Https Call Using Httpclient
The Name 'Controlname' Does Not Exist in the Current Context
Parallel.Foreach and Async-Await
Vb.Net Equivalent for C# 'Dynamic' with Option Strict On
Assigning Out/Ref Parameters in Moq
How to Load Dll 'Sqlite.Interop.Dll'
Byte Array to Image Conversion