How to get index using LINQ?
An IEnumerable
is not an ordered set.
Although most IEnumerables are ordered, some (such as Dictionary
or HashSet
) are not.
Therefore, LINQ does not have an IndexOf
method.
However, you can write one yourself:
///<summary>Finds the index of the first item matching an expression in an enumerable.</summary>
///<param name="items">The enumerable to search.</param>
///<param name="predicate">The expression to test the items against.</param>
///<returns>The index of the first matching item, or -1 if no items match.</returns>
public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate) {
if (items == null) throw new ArgumentNullException("items");
if (predicate == null) throw new ArgumentNullException("predicate");
int retVal = 0;
foreach (var item in items) {
if (predicate(item)) return retVal;
retVal++;
}
return -1;
}
///<summary>Finds the index of the first occurrence of an item in an enumerable.</summary>
///<param name="items">The enumerable to search.</param>
///<param name="item">The item to find.</param>
///<returns>The index of the first matching item, or -1 if the item was not found.</returns>
public static int IndexOf<T>(this IEnumerable<T> items, T item) { return items.FindIndex(i => EqualityComparer<T>.Default.Equals(item, i)); }
Get index of object in a list using Linq
You don't need to use LINQ
, you can use FindIndex
of List<T>
:
int index = customers.FindIndex(c => c.ID == 150);
Get List element position in c# using LINQ
var list = new List<int> { 3, 1, 0, 5 };
int pos = list.IndexOf(list.Min()); // returns 2
How can I get the index of an item in a list in a single step?
How about the List.FindIndex Method:
int index = myList.FindIndex(a => a.Prop == oProp);
This method performs a linear search; therefore, this method is an
O(n) operation, where n is Count.
If the item is not found, it will return -1
linq find in which position is my object in List
Use the IndexOf
method:
kriteriji.IndexOf(doc);
C# Linq Find all indexes of item in Listint within another Listint
var ResultList = List1.Select(x => List2.IndexOf(x));
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
.
LINQ way to get items between two indexes in a List
You can use list.Skip(startIndex).Take(endIndex - startIndex)
construct.
Where
startIndex
: is an index of the first item to select
endIndex
: is and index of the last item to select
Use LINQ to move item to top of list
LINQ is strong in querying collections, creating projections over existing queries or generating new queries based on existing collections. It is not meant as a tool to re-order existing collections inline. For that type of operation it's best to use the type at hande.
Assuming you have a type with a similar definition as below
class Item {
public int Id { get; set; }
..
}
Then try the following
List<Item> list = GetTheList();
var index = list.FindIndex(x => x.Id == 12);
var item = list[index];
list[index] = list[0];
list[0] = item;
Related Topics
Linq: from a List of Type T, Retrieve Only Objects of a Certain Subclass S
Split String into Smaller Strings by Length Variable
Get the Decimal Part from a Double
"Padding Is Invalid and Cannot Be Removed" Using Aesmanaged
Selecting Attribute Values with HTML Agility Pack
Return "Raw" JSON in ASP.NET Core 2.0 Web API
Calculate a Point Along the Line A-B at a Given Distance from A
Caching the Result from a [N Async] Factory Method Iff It Doesn't Throw
The Remote Server Returned an Unexpected Response: (413) Request Entity Too Large
How to Insert Characters to a File Using C#
Preventing Jit Inlining on a Method
JSONvalueproviderfactory Throws "Request Too Large"
How to Calculate Divide and Modulo for Integers in C#
C# Httpwebrequest the Underlying Connection Was Closed: an Unexpected Error Occurred on a Send
Foo.Cmd Won't Output Lines in Process (On Website)
Internal .Net Framework Data Provider Error 1025