I have a IEnumerable<T> list. - T is a custom type, one of the members of that type is an int called Id.
I also have a Dictionary<int, int>object the first int is an Id (this id will be in the IEnumerable<T> list. The second Int is a rating number.
I want to order the IEnumerable<T> list based on the rating inside Dictionary<int, int> - Highest First
I can do this by if statements and looping, but I have a feeling this can be done using a linq/lambda statement.
Any one got any ideas how this can be done?
I'm guessing something like list.OrderBy(x => x.id == Dictionaryname. something something something
just use the OrderByDescending
var sorted = list.OrderByDescending(x => dictionary[x.id])
You can simply do:
list.OrderByDescending(x => dictionary[x.id])
Related
I have a list of objects that have a name field on them.
I want to know if there's a way to tell if all the name fields are unique in the list.
I could just do two loops and iterate over the list for each value, but I wanted to know if there's a cleaner way to do this using LINQ?
I've found a few examples where they compare each item of the list to a hard coded value but in my case I want to compare the name field on each object between each other and obtain a boolean value.
A common "trick" to check for uniqueness is to compare the length of a list with duplicates removed with the length of the original list:
bool allNamesAreUnique = myList.Select(x => x.Name).Distinct().Count() == myList.Count();
Select(x => x.Name) transforms your list into a list of just the names, and
Distict() removes the duplicates.
The performance should be close to O(n), which is better than the O(n²) nested-loop solution.
Another option is to group your list by the name and check the size of those groups. This has the additional advantage of telling you which values are not unique:
var duplicates = myList.GroupBy(x => x.Name).Where(g => g.Count() > 1);
bool hasDuplicates = duplicates.Any(); // or
List<string> duplicateNames = duplicates.Select(g => g.Key).ToList();
While you can use LINQ to group or create a distinct list, and then compare item-wise with the original list, that incurs a bit of overhead you might not want, especially for a very large list. A more efficient solution would store the keys in a HashSet, which has better lookup capability, and check for duplicates in a single loop. This solution still uses a little bit of LINQ so it satisfies your requirements.
static public class ExtensionMethods
{
static public bool HasDuplicates<TItem,TKey>(this IEnumerable<TItem> source, Func<TItem,TKey> func)
{
var found = new HashSet<TKey>();
foreach (var key in source.Select(func))
{
if (found.Contains(key)) return true;
found.Add(key);
}
return false;
}
}
If you are looking for duplicates in a field named Name, use it like this:
var hasDuplicates = list.HasDuplicates( item => item.Name );
If you want case-insensitivity:
var hasDuplicates = list.HasDuplicates( item => item.Name.ToUpper() );
I have a list with elements that I wanted to group by the value of a property. Later I would like to create a dictionary which key is this value that I used to group and the value a list (or IEnumerable) of the elements that are each group.
I am trying something like that:
Dictionary<long, Ienumerable<MyType>> dic = lstWithElements.GroupBy(x=>x.ID).ToDictionary(x=>x.????)
But in the ToDictionary method I don't have the ID property. So, how could I create my dictionary with the grouped items?
The overload of GroupBy that you're using returns an IEnumerable<IGrouping<long, MyType>>. IGrouping<long, MyType> provides a Key property of type long, representing the projected value by which elements were grouped, and also implements IEnumerable<MyType>.
So essentially, what you need is:
var dic = lstWithElements.GroupBy(x => x.ID).ToDictionary(x => x.Key);
Note: As pointed out in comments, this produces an IDictionary<long, IGrouping<long, MyType>>. This isn't really a problem, as long as you're only retrieving elements from the dictionary, and not trying to add new IEnumerable<MyType>s later on (which seems unlikely). If you do need precisely an IDictionary<long, IEnumerable<long, MyType>>, use the code outlined in this answer.
The ToDictionary method has a couple of overloads, but since your Dictionary uses an IEnumerable<MyType> for its Value, you're probably interested in the overload that accepts two parameters: a key selector, and an element selector.
Dictionary<long, IEnumerable<MyType>> dic = lstWithElements.GroupBy(x=>x.ID).ToDictionary(x=> x.Key, x => x.AsEnumerable());
Try this:
Dictionary<long, IGrouping<long,MyType>> dic = lstWithElements.GroupBy(x=>x.ID).ToDictionary(x=>x.Key)
I presume, that your data structure is at minimum this:
class MyType //or struct
{
long ID;
};
You want a list:
List<MyType> list;//with instances of MyType
either with different instances of MyType and same ID(making ID non-unique, is not best design perhaps) or some instances are in the list multiple times, what seems to be a better case, but either will work for question asked.
Now, GroupBy, what it does? List
List<MyType>
is transformed to
IEnumerable<MyType>
then GroupBy(x => x.ID) is grouping and providing:
IEnumerable<IGrouping<long, MyType>>
so we get elements of
IGrouping<long, MyType>
Now IGrouping knows everything IEnumerable does, interface inheritance, plus it has Key. So if you want your expected dictionary type:
Dictionary<long,IEnumerable<MyType>>
you have to do this:
var dictionary =
list
.GroupBy(x => x.ID)
.ToDictionary(x => x.ID, x => x.AsEnumerable())
;
ToDictionary allows to chose the Key from elements and also allows to transform Value stored for given key, so we can use this approach and call
x.AsEnumerable()
as IGrouping is inherited from IEnumerable.
Hope this longer explanation helps :).
I have the following code working with Tuples. Input is list of items, output is list of tuples and we need to calculate number of items for each date basically.
List<Tuple<DateTime, int>> list = new List<Tuple<DateTime, int>>();
foreach (ItemClass item in items)
{
foreach(Tuple<DateTime, int> tuple in list)
{
if (tuple.Item1 == item.date)
{
tuple.Item2++;
continue;
}
}
list.Add(Tuple.Create<DateTime, int>(item.date, 1));
}
This code currently doesn't compile because Item2 is read-only, the question is how to make it work?
Earlier this worked with the Dictionary but I had to remove it because it was not acceptable for outer code to work with the Dictionary.
Tuples are not intended for use in scenarios where mutability is required. You could make your own class that combines a DateTime with a mutable integer counter, but you can also do it with LINQ, converting to a list of tuples at the very end:
var list = items
.GroupBy(item => item.date)
.Select(g => Tuple.Create(g.Key, g.Count()))
.ToList();
The above code creates a group for each date, and then produces tuples only when the final counts of items in each group are known.
Try using Linq, GroupBy()to group by date, then use Select() and create a tuple for each group and finally convert to a list using ToList(). Something like
var result = items.GroupBy(x => x.Date)
.Select(x => Tuple.Create(x.Key, x.Count()))
.ToList();
I'm assuming because it's read only it already has a property, I think I've used tuple before so yeah, it probably does.
maybe you can't edit it because you can edit iterators in the Foreach() loop, perhaps experiment with another kind of loop.
OR
Set the item2 object to an object outside of the current loop and use that instead of the iterator.
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);
}
}
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();