Implicit Index or Generating Index in LINQ - c#

I recently encounter a couple of cases where it makes me wonder if there is any way to get internal index, or if not, to generate index efficiently when using LINQ.
Consider the following case:
List<int> list = new List() { 7, 4, 5, 1, 7, 8 };
In C#, if we are to return the indexes of "7" on the above array using LINQ, we cannot simply using IndexOf/LastIndexOf - for it will only return the first/last result.
This will not work:
var result = list.Where(x => x == 7).Select(y => list.IndexOf(y));
We have several workarounds for doing it, however.
For instance, one way of doing it could be this (which I typically do):
int index = 0;
var result = from x in list
let indexNow = index++
where x == 7
select indexNow;
It will introduce additional parameter indexNow by using let.
And also another way:
var result = Enumerable.Range(0, list.Count).Where(x => list.ElementAt(x) == 7);
It will generate another set of items by using Enumerable.Range and pick the result from it.
Now, I am wondering if there is any alternative, simpler way of doing it, such as:
if there is any (built-in) way to get the internal index of the IEnumerable without declaring something with let or
to generate the index for the IEnumerable using something other than Enumerable.Range (perhaps something like new? Which I am not too familiar how to do it), or
anything else which could shorten the code but still getting the indexes of the IEnumerable.

From IEnumerable.Select with index, How to get index using LINQ?, and so on: IEnumerable<T>.Select() has an overload that provides an index.
Using this, you can:
Project into an anonymous type (or a Tuple<int, T> if you want to expose it to other methods, anonymous types are local) that contains the index and the value.
Filter those results for the value you're looking for.
Project only the index.
So the code will look like this:
var result = list.Select((v, i) => new { Index = i, Value = v })
.Where(i => i.Value == 7)
.Select(i => i.Index);
Now result will contain an enumerable containing all indexes.
Note that this will only work for source collection types that guarantee insertion order and provide a numeric indexer, such as List<T>. When you use this for a Dictionary<TKey, TValue> or HashSet<T>, the resulting indexes will not be usable to index into the dictionary.

Related

C# array.sort() for multiple arrays in Descending order

I Have two arrays named weights and values. I wanted to sort Values based on the sorting of Weights. That works perfectly fine by doing
Array.Sort(Weights,Values);
This gives me arrays sorted in ascending order. I wanted to do the same sorting in Descending order. Is there a better way to do without using
Array.Reverse(Weights) and Array.Reverse(Values)
You'll have to use this overload and provide a custom IComparer<T>. The relatively new Comparer<T>.Create method makes this a lot easier because you can simply turn a delegate or lambda expression into an IComparer<T> without having to code a full implementation yourself. It's not clear from the question what the datatype of Weights and Values are, but here's an example using double[] and int[] respectively:
var Weights = new [] { 1.7, 2.4, 9.1, 2.1, };
var Values = new [] { 7, 9, 5, 3, };
Array.Sort(Weights, Values, Comparer<double>.Create((x, y) => y.CompareTo(x)));
And just for fun, here's a solution using LINQ:
var pairs = Weights.Zip(Values, Tuple.Create);
var orderedPairs = pairs.OrderByDescending(x => x.Item1);
I'd also recommend that you consider using a class to store weights and values together rather than as two separate arrays.
First, create a structure that holds the corresponding items.
var items =
Weights
.Select((weight, index) =>
new
{
Weight = weight,
Value = Values[index]
}
)
.OrderByDescending(item => item.Weight)
.ToArray();
Then you can get the sorted array back:
Weights = items.Select(item => item.Weight).ToArray();
Values = items.Select(item => item.Value).ToArray();
But you may also try one of the answers here:
Better way to sort array in descending order

LINQ to find array indexes of a value

Assuming I have the following string array:
string[] str = new string[] {"max", "min", "avg", "max", "avg", "min"}
Is it possbile to use LINQ to get a list of indexes that match one string?
As an example, I would like to search for the string "avg" and get a list containing
2, 4
meaning that "avg" can be found at str[2] and str[4].
.Select has a seldom-used overload that produces an index. You can use it like this:
str.Select((s, i) => new {i, s})
.Where(t => t.s == "avg")
.Select(t => t.i)
.ToList()
The result will be a list containing 2 and 4.
Documentation here
You can do it like this:
str.Select((v,i) => new {Index = i, Value = v}) // Pair up values and indexes
.Where(p => p.Value == "avg") // Do the filtering
.Select(p => p.Index); // Keep the index and drop the value
The key step is using the overload of Select that supplies the current index to your functor.
You can use the overload of Enumerable.Select that passes the index and then use Enumerable.Where on an anonymous type:
List<int> result = str.Select((s, index) => new { s, index })
.Where(x => x.s== "avg")
.Select(x => x.index)
.ToList();
If you just want to find the first/last index, you have also the builtin methods List.IndexOf and List.LastIndexOf:
int firstIndex = str.IndexOf("avg");
int lastIndex = str.LastIndexOf("avg");
(or you can use this overload that take a start index to specify the start position)
First off, your code doesn't actually iterate over the list twice, it only iterates it once.
That said, your Select is really just getting a sequence of all of the indexes; that is more easily done with Enumerable.Range:
var result = Enumerable.Range(0, str.Count)
.Where(i => str[i] == "avg")
.ToList();
Understanding why the list isn't actually iterated twice will take some getting used to. I'll try to give a basic explanation.
You should think of most of the LINQ methods, such as Select and Where as a pipeline. Each method does some tiny bit of work. In the case of Select you give it a method, and it essentially says, "Whenever someone asks me for my next item I'll first ask my input sequence for an item, then use the method I have to convert it into something else, and then give that item to whoever is using me." Where, more or less, is saying, "whenever someone asks me for an item I'll ask my input sequence for an item, if the function say it's good I'll pass it on, if not I'll keep asking for items until I get one that passes."
So when you chain them what happens is ToList asks for the first item, it goes to Where to as it for it's first item, Where goes to Select and asks it for it's first item, Select goes to the list to ask it for its first item. The list then provides it's first item. Select then transforms that item into what it needs to spit out (in this case, just the int 0) and gives it to Where. Where takes that item and runs it's function which determine's that it's true and so spits out 0 to ToList, which adds it to the list. That whole thing then happens 9 more times. This means that Select will end up asking for each item from the list exactly once, and it will feed each of its results directly to Where, which will feed the results that "pass the test" directly to ToList, which stores them in a list. All of the LINQ methods are carefully designed to only ever iterate the source sequence once (when they are iterated once).
Note that, while this seems complicated at first to you, it's actually pretty easy for the computer to do all of this. It's not actually as performance intensive as it may seem at first.
While you could use a combination of Select and Where, this is likely a good candidate for making your own function:
public static IEnumerable<int> Indexes<T>(IEnumerable<T> source, T itemToFind)
{
if (source == null)
throw new ArgumentNullException("source");
int i = 0;
foreach (T item in source)
{
if (object.Equals(itemToFind, item))
{
yield return i;
}
i++;
}
}
You need a combined select and where operator, comparing to accepted answer this will be cheaper, since won't require intermediate objects:
public static IEnumerable<TResult> SelectWhere<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, bool> filter, Func<TSource, int, TResult> selector)
{
int index = -1;
foreach (var s in source)
{
checked{ ++index; }
if (filter(s))
yield return selector(s, index);
}
}

remove all element except from given index number

I have following list and how can I remove with linq all elements from given index number:
List<string> a = new List<string>();
a.Add("number1");
a.Add("number2");
a.Add("number3");
How can I remove all element just except element which is index number =2 using linq.
LINQ isn't about removing things - it's about querying.
You can call RemoveRange to remove a range of items from a list though. So:
a.RemoveRange(0, 2);
will leave just "number3".
Or you could create a new list as per dasblinkenlight's answer. If you can tell us more about what you're trying to achieve and why you think LINQ is the solution, we may be able to help you more.
EDIT: Okay, now we have clearer requirements, you can use LINQ:
var newList = a.Where((value, index) => index != 2)
.ToList();
Assume you have list of indices you want to keep, you can use Where with index to filter:
var indexList = new[] {2};
var result = a.Where((s, index) => indexList.Contains(index));
An equivalent operation to "remove everything but X" is "keep X". The simplest way to do it is constructing a new list with a single element at index 2, like this:
a = new List<string>{a[2]};
Although #dasblinkenlight's answer is the better option, here is the linq (or at least one iteration)
a.Where((item,index) => b1 == 2);
or to return a single string objects rather than an IEnumberable
a.Where((a1,b1) => b1 == 2).First();

Auto-incrementing a generic list using LINQ in C#

Is there a good way to provide an "auto-increment" style index column (from 1..x) when projecting items using LINQ?
As a basic example, I'm looking for the index column below to go from 1 to the number of items in list.
var items = from s1 in list
select new BrowsingSessionItemModel { Id = s1.Id, Index = 0 };
Iterating through the list would be the easy option but I was wondering if there was a better way to do this?
You can't do this with LINQ expressions. You could use the following .Select extension method though:
var items = list.Select((x, index) => new BrowsingSessionItemModel {
Id = x.Id,
Index = index
});
You can use the overload of Select which takes the provides the index to the projection as well:
var items = list.Select((value, index) => new BrowsingSessionItemModel {
Id = value.Id,
Index = index
});
Note that there is no query expression support for this overload. If you're actually fetching the values from a database (it's not clear whether list is really a List<T>) you should probably make sure you have an appropriate ordering, as otherwise the results are somewhat arbitrary.

Sort one list by another

I have 2 list objects, one is just a list of ints, the other is a list of objects but the objects has an ID property.
What i want to do is sort the list of objects by its ID in the same sort order as the list of ints.
Ive been playing around for a while now trying to get it working, so far no joy,
Here is what i have so far...
//**************************
//*** Randomize the list ***
//**************************
if (Session["SearchResultsOrder"] != null)
{
// save the session as a int list
List<int> IDList = new List<int>((List<int>)Session["SearchResultsOrder"]);
// the saved list session exists, make sure the list is orded by this
foreach(var i in IDList)
{
SearchData.ReturnedSearchedMembers.OrderBy(x => x.ID == i);
}
}
else
{
// before any sorts randomize the results - this mixes it up a bit as before it would order the results by member registration date
List<Member> RandomList = new List<Member>(SearchData.ReturnedSearchedMembers);
SearchData.ReturnedSearchedMembers = GloballyAvailableMethods.RandomizeGenericList<Member>(RandomList, RandomList.Count).ToList();
// save the order of these results so they can be restored back during postback
List<int> SearchResultsOrder = new List<int>();
SearchData.ReturnedSearchedMembers.ForEach(x => SearchResultsOrder.Add(x.ID));
Session["SearchResultsOrder"] = SearchResultsOrder;
}
The whole point of this is so when a user searches for members, initially they display in a random order, then if they click page 2, they remain in that order and the next 20 results display.
I have been reading about the ICompare i can use as a parameter in the Linq.OrderBy clause, but i can’t find any simple examples.
I’m hoping for an elegant, very simple LINQ style solution, well I can always hope.
Any help is most appreciated.
Another LINQ-approach:
var orderedByIDList = from i in ids
join o in objectsWithIDs
on i equals o.ID
select o;
One way of doing it:
List<int> order = ....;
List<Item> items = ....;
Dictionary<int,Item> d = items.ToDictionary(x => x.ID);
List<Item> ordered = order.Select(i => d[i]).ToList();
Not an answer to this exact question, but if you have two arrays, there is an overload of Array.Sort that takes the array to sort, and an array to use as the 'key'
https://msdn.microsoft.com/en-us/library/85y6y2d3.aspx
Array.Sort Method (Array, Array)
Sorts a pair of one-dimensional Array objects (one contains the keys
and the other contains the corresponding items) based on the keys in
the first Array using the IComparable implementation of each key.
Join is the best candidate if you want to match on the exact integer (if no match is found you get an empty sequence). If you want to merely get the sort order of the other list (and provided the number of elements in both lists are equal), you can use Zip.
var result = objects.Zip(ints, (o, i) => new { o, i})
.OrderBy(x => x.i)
.Select(x => x.o);
Pretty readable.
Here is an extension method which encapsulates Simon D.'s response for lists of any type.
public static IEnumerable<TResult> SortBy<TResult, TKey>(this IEnumerable<TResult> sortItems,
IEnumerable<TKey> sortKeys,
Func<TResult, TKey> matchFunc)
{
return sortKeys.Join(sortItems,
k => k,
matchFunc,
(k, i) => i);
}
Usage is something like:
var sorted = toSort.SortBy(sortKeys, i => i.Key);
One possible solution:
myList = myList.OrderBy(x => Ids.IndexOf(x.Id)).ToList();
Note: use this if you working with In-Memory lists, doesn't work for IQueryable type, as IQueryable does not contain a definition for IndexOf
docs = docs.OrderBy(d => docsIds.IndexOf(d.Id)).ToList();

Categories