I have a List<List>. I want to get a single List from that.
List<int> from List<List<SomeClass>()
For loop is an obvious solution but i want something more better and eligent from performance point of view.
List<List<Employee>> ValueLists;
List<int> Current= ValueLists.SelectMany(u=>u.Select(v=>v.EmployeeID));
Try this:
var list = listOfLists.SelectMany(x => x).ToList();
I'm not sure exactly what extra info you're after. The edit you made to the question is almost complete code.
You should have written:
List<int> Current =
ValueLists
.SelectMany(u => u.Select(v => v.EmployeeID))
.ToList();
This could be written as this instead:
var query =
from u in ValueLists
from v in u
select v.EmployeeID;
List<int> Current = query.ToList();
Maybe that gives more clarity.
Still don't get the answer, Please see the editted question for more
details and actual scenario:
List<List<Employee>> ValueLists;
List<int> Current= ValueLists.SelectMany(u=>u.Select(v=>v.EmployeeID));
Your approach doesn't work because an IEnumerable<int> is not a List<int>. Therefor you need the ToList() at the end.
This should work:
List<int> Current = ValueLists.SelectMany(u => u.Select(e => e.EmployeeID)).ToList();
Reimplementing LINQ to Objects: Part 9 - SelectMany
Enumerable.SelectMany
What about:
var list = listOfLists.SelectMany(x => x.EmployeeID).ToList();
Related
I would like to Zip multiple List of integer and don't know how to do that in LinQ.
Here's my List :
List<KeyValuePair<Guid, List<int>>> totals = Totals.Where(x => x.Key == myGuid).ToList();
//where Totals is a List<KeyValuePair<Guid, List<int>>>
List<List<int>> totalsValue = totals.Select(s => s.Value).ToList();
//I want to Zip all my List<int> in totalsValue and put it into listToReturn
List<int> listToReturn = new List<int>();
I want something like that : http://linqsamples.com/linq-to-objects/other/Zip-lambda-csharp but in this exemple, lists are separeted.
Mine is a List>
Where listToReturn represents the list to return.
Can someone help me ?
Result :
Where adventest is a List and agiltest also
enter image description here
I think you are looking for SelectMany:
List<int> listToReturn= totals = Totals.Where(x => x.Key == myGuid)
.SelectMany(s => s.Value)
.ToList();
What you are trying to do is flatten all the lists into one sequence and that is what SelectMany extension method do. Zip, in the other side, merges each element of the first sequence with an element that has the same index in the second sequence, in other words, it allows you to project from two sequences of the same length.
Update
Now I understand what you are trying to achieve:
var lists= Totals.Where(x => x.Key == myGuid).Select(e=>Value).ToList();// Select the lists
if(lists.Count>0)
var result= Enumerable.Range(0, lists[0].Count).Select(i=> lists.Sum(l=>l[i]));
The thing with this solution you need to make sure that all the selected lists have the same size. I'm pretty sure there is a more elegant solution but this was that come to my mind now. If I think in something better I will update my answer
I have a generic List List[int, myClass], and I would like to find the smallest int value, and retrieve the items from the list that match this.
I am generating this from another LINQ statement
var traysWithExtraAisles = (from t in poolTrays
where t.TrayItems.Select(i=>i.Aisle)
.Any(a=> ! selectedAisles.Contains(a))
select new
{
count= t.TrayItems.Select(i=>i.Aisle)
.Count(a=> !selectedAisles.Contains(a)),
tray=t
}).ToList();
this gives me my anonymous List of [count, Tray], but now I want to figure out the smallest count, and return a sublist for all the counts that match this.
Can anyone help me out with this?
var smallestGroup = traysWithExtraAisles
.GroupBy(x => x.count)
.OrderBy(g => g.Key)
.First();
foreach(var x in smallestGroup)
{
var poolTray = x.tray;
}
You can use SelectMany to "flatten" your list. Meaning, combine all of the lists into one, then take the Min. So;
int minimum = poolTrays.SelectMany(x => x).Min(x => x.TheIntegerIWantMinOf);
Will give you the smallest value contained in the sub lists. I'm not entirely sure this is what you're asking for but if your goal is simply to find the smallest element in the collection then I would scrap the code you posted and use this instead.
Right, I now realise this is actually incredibly easy to do with a bit more fiddling around. I have gone with
int minCount = traysWithExtraAisles.Min(x=>x.count);
var minAislesList = (from t in trayswithExtraAisles
where t.count==mincount
select t).ToList()
I imagine it is probably possible to do this in one statement
You can use GroupBy as answered by Tim... or OrderBy as follow:
var result = traysWithExtraAisles.OrderBy(x=>x.count)
.TakeWhile((x,i)=> i == 0 || x.count == traysWithExtraAisles[i-1]).count;
I have a List<int> ListOfIDs containing some numbers which are IDs.
I have a List<CustomClass> ListOfObjects containing some objects, which properties reflecting their IDs.
I've searched high and low for a Linq query that will allow me to return from my List a sublist of only those objects which have an ID that is contained within the List.
My attempt does not compile and I cannot seem to correct the syntax :
List<CustomClass> SubList = ListOfObjects.Where(ListOfIDs.Contains(p => p.ID))
Thanks very much.
I think you want to do like this?
List<CustomClass> SubList = ListOfObjects
.Where(obj => ListOfIDs.Contains(obj.ID))
.ToList();
I think this is what you need:
List<CustomClass> SubList = ListOfObjects.Where(p => ListOfIDs.Contains(p.ID)).ToList();
Don't forget to call ToList() in the end.
Also consider using HashSet for ListOfIDs, because complexity of Contains operation is just O(1). But, well it depends on how much data you have.
Here's the correct syntax for what you're trying to do:
... ListOfObjects.Where(p => ListOfIDs.Contains(p.ID)).ToList();
Though this might be faster that the Where(Contains) method:
var sublist = (
from obj in ListOfObjects
join id in ListOfIDs on id equals obj.ID
select obj ).ToList();
Try to use this piece of code snippet:
List<CustomClass> SubList = ListOfObjects.Where(o => ListOfIDs.Contains(o.ID))
.ToList();
I have two lists
List<T> list1 = new List<T>();
List<T> list2 = new List<T>();
I want remove all elements from list1, which also exist in list2. Of course I can loop through the first loop looking for each element in list2, but I am looking for elegant solution.
Thanks!
To change the actual list1 in place, you could use
list1.RemoveAll(item => list2.Contains(item));
You might instead prefer to simply have a query over the lists without modifying either
var result = list1.Except(list2);
LukeH makes a good recommendation in the comments. In the first version, and if list2 is particularly large, it might be worth it to load the list into a HashSet<T> prior to the RemoveAll invocation. If the list is small, don't worry about it. If you are unsure, test both ways and then you will know.
var theSet = new HashSet<YourType>(list2);
list1.RemoveAll(item => theSet.Contains(item));
With LINQ:
var result = list1.Except(list2);
list1.RemoveAll( item => list2.Contains(item));
Description
I think you mean the generic type List<Type>. You can use Linq to do this
Sample
List<string> l = new List<string>();
List<string> l2 = new List<string>();
l.Add("one");
l.Add("two");
l.Add("three");
l2.Add("one");
l2.Add("two");
l2.Add("three");
l2.Add("four");
l2.RemoveAll(x => l.Contains(x));
More Information
MSDN - List.RemoveAll Method
var result = list1.Except(list2);
Using LINQ you can do this:
List1.RemoveAll(i => !List2.Contains(i));
If you want to remove a list of objects (list2) from another list (list1) use:
list1 = list1.Except(list2).ToList()
Remember to use ToList() to convert IEnumerable<T> to List<T>.
var NewList = FirstList.Where(a => SecondList.Exists(b => b.ID != a.ID));
Using LINQ
How can I sort generic list DESC and ASC? With LINQ and without LINQ? I'm using VS2008.
class Program
{
static void Main(string[] args)
{
List<int> li = new List<int>();
li.Add(456);
li.Add(123);
li.Add(12345667);
li.Add(0);
li.Add(1);
li.Sort();
foreach (int item in li)
{
Console.WriteLine(item.ToString() + "\n");
}
Console.ReadKey();
}
}
With Linq
var ascendingOrder = li.OrderBy(i => i);
var descendingOrder = li.OrderByDescending(i => i);
Without Linq
li.Sort((a, b) => a.CompareTo(b)); // ascending sort
li.Sort((a, b) => b.CompareTo(a)); // descending sort
Note that without Linq, the list itself is being sorted. With Linq, you're getting an ordered enumerable of the list but the list itself hasn't changed. If you want to mutate the list, you would change the Linq methods to something like
li = li.OrderBy(i => i).ToList();
Without Linq:
Ascending:
li.Sort();
Descending:
li.Sort();
li.Reverse();
without linq,
use Sort() and then Reverse() it.
I was checking all the answer above and wanted to add one more additional information.
I wanted to sort the list in DESC order and I was searching for the solution which is faster for bigger inputs and I was using this method earlier :-
li.Sort();
li.Reverse();
but my test cases were failing for exceeding time limits, so below solution worked for me:-
li.Sort((a, b) => b.CompareTo(a));
So Ultimately the conclusion is that 2nd way of Sorting list in Descending order is bit faster than the previous one.
Very simple way to sort List with int values in Descending order:
li.Sort((a,b)=> b-a);
Hope that this helps!