score:0
while reading other answers i got a little confused about which indexes
order you want exactly, but here's solution if you want them to in order 1 2 0
as you posted in your question. try this:
var a = new int[] { 2, 3, 1 };
var indexes = new int [a.length];
var sorted = a.orderby(n => n)
.select((n, i) =>
{
indexes[array.indexof(a, n)] = i;
return n;
})
.toarray();
score:1
another working solution:
var input = new list<int> { 2, 3, 1 };
var result = input.select(x => input.orderby(n => n).tolist().indexof(x));
console.writeline(string.join(" ", result)); // 1 2 0
score:4
one way to do this is as follows:
int[] a = {2, 3, 1};
int[] b = enumerable.range(0, a.length).toarray();
int[] c = new int[a.length];
array.sort(a, b);
for (int i = 0; i < b.length; ++i)
c[b[i]] = i;
console.writeline(string.join(", ", c)); // prints 1, 2, 0
it uses the overload of array.sort()
which sorts one array using the values from a different array.
i think this is fairly efficient: it uses a o(n log(n)) sort and an o(n) remapping. (the other correct solutions are o(n log(n)) plus o(n^2))
it only works with arrays, however (because there is no equivalent of array.sort()
for list).
an alternative using linq (and effectively an amendment to @nawfal's answer):
int[] a = {2, 3, 1};
var b = a
.select((item, index) => new { item, index })
.orderby(x => x.item)
.select(x => x.index)
.toarray();
int[] c = new int[b.length];
for (int i = 0; i < b.length; ++i)
c[b[i]] = i;
console.writeline(string.join(", ", c)); // prints 1, 2, 0
the crucial thing here is the additional mapping step in both approaches:
int[] c = new int[b.length];
for (int i = 0; i < b.length; ++i)
c[b[i]] = i;
this is effectively a reverse-lookup mapping.
score:8
you could do this with a linq select:
var a =new [] {2,3,1};
var sorted = a.orderby (x => x).tolist();
var indexes = a.select (x => sorted.indexof(x));
if this is a huge list rather than this simple one it might be a little inefficient but does return what you are expecting.
score:23
note:
i made a terrible mistake of misreading op's question (and embarrassed this received so many upvotes). i wished (ideally) op accepts one of the other answers as correct. to do justice to the upvoters and in spirit of so, i will amend this answer to make it correct.
one could carry two extension methods, one for old indices and one for new indices (which is what op wants).
public static ienumerable<int> oldindicesifsorted<t>(this ienumerable<t> source) where t : icomparable<t>
{
return source
.select((item, index) => new { item, index })
.orderby(a => a.item)
.select(a => a.index);
}
public static ienumerable<int> newindicesifsorted<t>(this ienumerable<t> source) where t : icomparable<t>
{
return source
.oldindicesifsorted()
.select((oldindex, index) => new { oldindex, index })
.orderby(a => a.oldindex)
.select(a => a.index);
}
call it like,
//a = [2, 3, 1];
a.newindicesifsorted(); // should print [1, 2, 0]
the two methods are lazy, but newindicesifsorted
should ideally be written according to matthew watson's answer which is simply more efficient. the plus side of both mine and mat's answer is that is handles duplicate entries well.
Source: stackoverflow.com
Related Query
- Get new indices of items in a collection after sorting using LINQ
- How to get the number of items in a collection using LINQ
- Using LINQ to get items from same collection where numbers are logical following
- Using LINQ to Objects to find items in one collection that do not match another
- Using Linq to find the element after a specified element in a collection
- Order of items after using LINQ Select extension method
- Trying to get all elements after first match using linq
- Using LINQ to get the results from another LINQ collection
- Using Linq and C#, trying to get two lists from a list of master items grouped by two inner lists
- LINQ - C# - Using lambda - Get a set of data from a Collection
- Get Alphabetical List Of Items in Collection Using Lambda/Linq?
- Get a count of a linked collection using OData and LINQ
- Find indices of particular items in the list using linq
- How to get strongly-typed collection from XML using Linq
- Using LINQ to get a list of items where the item contains a part of an item from another list
- Get Specific object after a join using LINQ
- Optimized way to select items from a Collection excluding a list of certain member using Linq
- Get Index of a String Array after Split using LINQ
- Get Min and Max for items from database using Linq
- How can I get the top three players and their high scores from a collection using linq and lambdas
- Get a comma separated list of entity collection using linq
- How do I get the first value from this collection using Linq to Entities?
- Using Linq to get groups from a collection
- using linq to merge items together in a collection
- Remove items from collection using linq
- Using LINQ to get distinct items that do not join
- Get distinct items from DataTable using LINQ
- How to get the second repeated item from a collection of objects using LINQ to object
- Get a strongly typed list of unique items using LINQ GroupBy() from database
- How to get columns of both datatable after innerjoining them using linq
More Query from same tag
- SubQuery using Lambda Expression
- LINQ : select all that match a single field, merge on original
- LINQ Left Outer Join only the first record
- Understanding Execution in LINQ
- Generic ValidationAttribute with dynamic Entity.Property unique check (set at run time)
- LINQ how do I specify select certain columns in a one to many joins
- Reduce a list into smaller lists of two using LINQ (Functional Programming)
- LINQ query Where ID does not exist as a property in a list of objects
- Linq UNION ALL on same DataTable?
- Convert linq result to name value pair
- How to create a simple left outer join in lambda expression in EF ASP.NET MVC5
- How do I filter a strongly typed list with List<String> variables
- How to break link between source collection and LINQ result
- Sorting List of Table objects by their Relations
- Doing Sum() on a set of anonymous type: is it possible?
- Can't use == in LINQ Extension Method
- Linq syntax required for string array to string conversion
- EF LINQ outer join not using conditional values
- How do you retrieve records and all child records in one database hit in ADO.NET Entities?
- Querying a List of objects to find the the day of the week with the most items
- ?? operator didn't trigger System.DBNull type in DataTable DataRow
- Need help in resolving error in predicates for And operator in LINQ
- Get Records from table where quantity is not between fromquantity and ToQuantity using Linq to SQL
- EF Core “InvalidOperationException: Include has been used on non entity queryable” on IQueryable
- c# build hierarchy in reverse
- How do I identify which Linq functions will not call to sql multiple times?
- Linq == null vs IsNullOrEmpty -- Different or Same?
- Limit results from linq results .NET
- linq grouping by custom class
- Merge two LINQ expressions into one