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
Related
Background: I have two Collections of different types of objects with different name properties (both strings). Objects in Collection1 have a field called Name, objects in Collection2 have a field called Field.
I needed to compare these 2 properties, and get items from Collection1 where there is not a match in Collection2 based on that string property (Collection1 will always have a greater or equal number of items. All items should have a matching item by Name/Field in Collection2 when finished).
The question: I've found answers using Lists and they have helped me a little(for what it's worth, I'm using Collections). I did find this answer which appears to be working for me, however I would like to convert what I've done from query syntax (if that's what it's called?) to a LINQ query. See below:
//Query for results. This code is what I'm specifically trying to convert.
var result = (from item in Collection1
where !Collection2.Any(x => x.ColumnName == item.FieldName)
select item).ToList();
//** Remove items in result from Collection1**
//...
I'm really not at all familiar with either syntax (working on it), but I think I generally understand what this is doing. I'm struggling trying to convert this to LINQ syntax though and I'd like to learn both of these options rather than some sort of nested loop.
End goal after I remove the query results from Collection1: Collection1.Count == Collection2 and the following is true for each item in the collection: ItemFromCollection1.Name == SomeItemFromCollection2.Field (if that makes sense...)
You can convert this to LINQ methods like this:
var result = Collection1.Where(item => !Collection2.Any(x => x.ColumnName == item.FieldName))
.ToList();
Your first query is the opposite of what you asked for. It's finding records that don't have an equivalent. The following will return all records in Collection1 where there is an equivalent:
var results=Collection1.Where(c1=>!Collection2.Any(c2=>c2.Field==c1.Name));
Please note that this isn't the fastest approach, especially if there is a large number of records in collection2. You can find ways of speeding it up through HashSets or Lookups.
if you want to get a list of non duplicate values to be retained then do the following.
List<string> listNonDup = new List<String>{"6","1","2","4","6","5","1"};
var singles = listNonDup.GroupBy(n => n)
.Where(g => g.Count() == 1)
.Select(g => g.Key).ToList();
Yields: 2, 4, 5
if you want a list of all the duplicate values then you can do the opposite
var duplicatesxx = listNonDup.GroupBy(s => s)
.SelectMany(g => g.Skip(1)).ToList();
I have a SortedDictionary of the type:
SortedDictionary<PriorityType, List<T>> dictionary;
where PriorityType is an Enum class, and the List contains various string values.
I want to use LINQ to search for the string items in the list, that have an even length.
As in:
IEnumerable<T> filteredList = new List<T>();
// Stores items in list whose string length is even
filteredList = //LINQ code;
I have tried a lot of implementations of LINQ but, it seems tough to traverse a List in a SortedDictionary using LINQ (taking into account I'm relatively new to LINQ).
Please help me with the LINQ code. Thanks!
If I understand you correctly, then you need items from lists which have even count of items:
filteredList = dictionary.Select(kvp => kvp.Value)
.Where(l => l != null && l.Count % 2 == 0)
.SelectMany(l => l)
.ToList();
UPDATE: If you want to select strings with even length, then you should use List<string> instead of generic list of T:
SortedDictionary<PriorityType, List<string>> dictionary;
filteredList = dictionary.SelectMany(kvp => kvp.Value)
.Where(s => s.ToString().Length % 2 == 0)
.ToList();
The solution provided by #Sergey is correct & in conformance to my requirements.
Also I found another easy solution using the select statement.
filteredList = from list in dictionary.Values from item in list where item.ToString().Length % 2 == 0 select item;
Hope this helps!
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 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();