I have two collections that I get from functions:
IEnumerable<InventoryItem> inventoryItems = get();
IEnumerable<InventoryItem> relatedItems = get();
I want to assign related items to each inventory item. But, related item can't match the inventory item itself. Meaning inventory item cant have itself for related item.
I am trying to skip the overlapping elements in the collection this way:
foreach (var item in inventoryItems)
{
InventoryItem item1 = item;
relatedItems.SkipWhile(x => x.RelatedItems.Contains(item1)).ForEach(i => item1.RelatedItems.Add(i));
Save(item);
}
This does not seem to work. Do any of you Linq user have any better suggestions.
The problem that I have is with SkipWhile(x => x.RelatedItems.Contains(item1)) part. The other part works when matching items regardless if they overlap
Where with negative condition should filter out the only item you don't need (note that comapison with != may need to be replaced with some other condition that check item identity)
item1.RelatedItems = relatedItems
.Where(x => !x.RelatedItems.Any(r => r!= item1)).ToList();
Try this:
public IEnumerable<T> GetNotMatchingElements<T>(IEnumerable<T> collection1, IEnumerable<T> collection2)
{
var combinedCollection = collection1.Union(collection2);
var filteredCollection = combinedCollection.Except(collection1.Intersect(collection2));
return filteredCollection;
}
Not sure I completely understand, but if I do, this should work:
foreach (var invItem in inventoryItems)
{
invItem.RelatedItems = relatedItems
.Where(relItem => !relItem.RelatedItems.Contains(invItem)));
Save(invItem);
}
Related
I have a List<Map> and I wanted to update the Map.Target property based from a matching value from another List<Map>.
Basically, the logic is:
If mapsList1.Name is equal to mapsList2.Name
Then mapsList1.Target = mapsList2.Name
The structure of the Map class looks like this:
public class Map {
public Guid Id { get; set; }
public string Name { get; set; }
public string Target { get; set; }
}
I tried the following but obviously it's not working:
List<Map> mapsList1 = new List<Map>();
List<Map> mapsList2 = new List<Map>();
// populate the 2 lists here
mapsList1.Where(m1 => mapsList2.Where(m2 => m1.Name == m2.Name) ) // don't know what to do next
The count of items in list 1 will be always greater than or equal to the count of items in list 2. No duplicates in both lists.
Assuming there are a small number of items in the lists and only one item in list 1 that matches:
list2.ForEach(l2m => list1.First(l1m => l1m.Name == l2m.Name).Target = l2m.Target);
If there are more than one item in List1 that must be updated, enumerate the entire list1 doing a First on list2.
list1.ForEach(l1m => l1m.Target = list2.FirstOrDefault(l2m => l1.Name == l2m.Name)?.Target ?? l1m.Target);
If there are a large number of items in list2, turn it into a dictionary
var d = list2.ToDictionary(m => m.Name);
list1.ForEach(m => m.Target = d.ContainsKey(m.Name) ? d[m.Name].Target : m.Target);
(Presumably list2 doesn't contain any repeated names)
If list1's names are unique and everything in list2 is in list1, you could even turn list1 into a dictionary and enumerate list2:
var d=list1.ToDictionary(m => m.Name);
list2.ForEach(m => d[m.Name].Target = m.Target);
If List 2 has entries that are not in list1 or list1 has duplicate names, you could use a Lookup instead, you'd just have to do something to avoid a "collection was modified; enumeration may not execute" you'd get if you were trying to modify the list it returns in response to a name
mapsList1.Where(m1 => mapsList2.Where(m2 => m1.Name == m2.Name) ) // don't know what to do next
LINQ Where doesn't really work like that / that's not a statement in itself. The m1 is the entry from list1, and the inner Where would produce an enumerable of list 2 items, but it doesn't result in the Boolean the outer Where is expecting, nor can you do anything to either of the sequences because LINQ operations are not supposed to have side effects. The only thing you can do with a Where is capture or use the sequence it returns in some other operation (like enumerating it), so Where isn't really something you'd use for this operation unless you use it to find all the objects you need to alter. It's probably worth pointing out that ForEach is a list thing, not a LINQ thing, and is basically just another way of writing foreach(var item in someList)
If collections are big enough better approach would be to create a dictionary to lookup the targets:
List<Map> mapsList1 = new List<Map>();
List<Map> mapsList2 = new List<Map>();
var dict = mapsList2
.GroupBy(map => map.Name)
.ToDictionary(maps => maps.Key, maps => maps.First().Target);
foreach (var map in mapsList1)
{
if (dict.TryGetValue(map.Name, out var target))
{
map.Target = target;
}
}
Note, that this will discard any possible name duplicates from mapsList2.
I have a list of FirstLevelItems. Each item has a list of SecondLevelItems.
public class FirstLevelItem {
public List<SecondLevelItem> SecondLevelItems { get; set; }
}
public class SecondLevelItem{
public bool Deleted {get; set;}
}
I want to return all FirstLevelItems and filter SecondLevelItems which are Deleted.
I understand you have a local collection and you want to filter the items that are not deleted from each element. In such case you can use this:
items.ForEach( item =>
item.SecondLevelItems = item.SecondLevelItems.Where(s => !s.Deleted).ToList() );
Alternatively, if you are talking about a database, you could do:
var results = DataContext.FirstLevelItems.Select( fi => new {
FirstLevelItem = fi,
SecondLevelItems = fi.SecondLevelItems.Where( si => !si.Deleted )
} );
This will return tuples where FirstLevelItem property is the first level item itself, and SecondLevelItems property is the filtered list of second level items. However, make sure you access the SecondLevelItems property directly, not the FirstLevelItem.SecondLevelItems property, as that would lazily evaluate and query the database for all second level items.
It is interesting how everyone understood the problem differently :-) .
Return all FirstLevelItems that contain at least one SecondLevelItem that is deleted:
var result = DbContext.FirstLevelItems
.Where(fl => fl.SecondLevelItems.Any(sl => sl.Deleted));
The Any clause checks if a boolean condition is true for at least one item in a collection.
this code maybe help you
var fli = //get your FirstLevelItems
var result= fli.SecondLevelItems.Where(x => x.Deleted);
Suppose you have variable list of type List<FirstLevelItem>.
list = list.Select(listItem =>
{
listItem.SecondLevelItems = listItem
.SecondLevelItems
.Where(secondLevelItem => secondLevelItem.Deleted)
.ToList();
return listItem;
}).ToList();
I have a DB used for a production line. It has an Orders table, and Ordertracker table, an Item table, and an Itemtracker table.
Both Orders and Items have many-to-many relationships with status. The tracker tables resolves these relationships in such a way that an item can have multiple entries in the tracker - each with a particular status.
I tried to upload a picture of the tables to make things clearer but alas, I don't have enough points yet :C
I need to find items whose last status in the Itemtracker table meets a condition, either '3' or '0'.
I then need to get the first one of these items.
The steps I am using to accomplish this are as follows:
Get all the Orders which have a certain status.
Get all the Items in that Order.
Get all the Items whose last status was = 0 or 3.
Get the first of these items.
My code is as follows:
public ITEM GetFirstItemFailedOrNotInProductionFromCurrentOrder()
{
var firstOrder = GetFirstOrderInProductionAndNotCompleted();
var items = ERPContext.ITEM.Where(i => i.OrderID == firstOrder.OrderID) as IQueryable<ITEM>;
if (CheckStatusOfItems(items) != null)
{
var nextItem = CheckStatusOfItems(items);
return nextItem ;
}
else
{
return null;
}
}
private ITEM CheckStatusOfItems(IQueryable<ITEM> items)
{
List<ITEM> listOfItemsToProduce = new List<ITEM>();
foreach (ITEM item in items.ToList())
{
var lastStatusOfItem = ERPContext.ITEMTRACKER.Where(it => it.ItemID == item.ItemID)
.OrderByDescending(it => it.ItemTrackerID).FirstOrDefault();
if (lastStatusOfItem.ItemStatus == (int)ItemStatus.Failed || lastStatusOfItem.ItemStatus == (int)ItemStatus.Confirmed)
{
listOfItemsToProduce.Add(item);
}
}
return listOfItemsToProduce.FirstOrDefault();
}
Now, this all works fine and returns what I need but I'm aware that this might not be the best approach. As it is now my IQueryable collection of items will never contain more than 6 items - but if it could grow larger, then calling ToList() on the IQueryable and iterating over the results in-memory would probably not be a good idea.
Is there a better way to iterate through the IQueryable items to fetch out the items that have a certain status as their latest status without calling ToList() and foreaching through the results?
Any advice would be much appreciated.
Using LINQ query syntax, you can build declaratively a single query pretty much the same way you wrote the imperative iteration. foreach translates to from, var to let and if to where:
private ITEM CheckStatusOfItems(IQueryable<ITEM> items)
{
var query =
from item in items
let lastStatusOfItem = ERPContext.ITEMTRACKER
.Where(it => it.ItemID == item.ItemID)
.OrderByDescending(it => it.ItemTrackerID)
.FirstOrDefault()
where (lastStatusOfItem.ItemStatus == (int)ItemStatus.Failed || lastStatusOfItem.ItemStatus == (int)ItemStatus.Confirmed)
select item;
return query.FirstOrDefault();
}
or alternatively using from instead of let and Take(1) instead of FirstOrDefault():
private ITEM CheckStatusOfItems(IQueryable<ITEM> items)
{
var query =
from item in items
from lastStatusOfItem in ERPContext.ITEMTRACKER
.Where(it => it.ItemID == item.ItemID)
.OrderByDescending(it => it.ItemTrackerID)
.Take(1)
where (lastStatusOfItem.ItemStatus == (int)ItemStatus.Failed || lastStatusOfItem.ItemStatus == (int)ItemStatus.Confirmed)
select item;
return query.FirstOrDefault();
}
I have a list of items and I want to create two ways to sort them, Alphabetically and Last Modified.
Here's what I did:
// Alphabetically
tableItems = tableItems.OrderBy (MyTableItem => MyTableItem.ItemName).ToList();
reloadTable(tableItems);
// Last Modified
tableItems = tableItems.OrderBy (MyTableItem => MyTableItem.Timestamp).ToList();
reloadTable(tableItems);
and this works perfectly fine.
My problem is I want this happen to all items in the list except for one.
This one item will always be constant and I want to make sure it's ALWAYS on the top of the list.
What would I need to do for that?
if it matters, c# is the lang.
Thank you for your time.
tableItems = tableItems.OrderBy(i => i.ItemName != "yourexceptitem").ThenBy(i => i.Timestamp).ToList();
EDIT:
If you want to sort the itemname except one, do like this,
tableItems = tableItems.OrderBy(i => i.ItemName != "TestSubject3").ToList();
Other, generic solution:
public static IEnumerable<T> OrderByExcept<T>(
this IEnumerable<T> source,
Predicate<T> exceptPredicate,
Func<IEnumerable<T>, IOrderedEnumerable<T>> projection)
{
var rest = new List<T>();
using (var enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
if (exceptPredicate(enumerator.Current))
{
yield return enumerator.Current;
}
else
{
rest.Add(enumerator.Current);
}
}
}
foreach (var elem in projection(rest))
{
yield return elem;
}
}
Usage:
tableItems = tableItems.OrderByExcept(
item => item.ItemName == "TestSubject3",
items => items.OrderBy(MyTableItem => MyTableItem.ItemName)
.ThenBy(MyTableItem => MyTableItem.TimeStamp))
.ToList();
Items that meets predicate will always be on the top of list, to the rest of elements projection will be applied.
With the following object hierarchy, I need to confirm whether or not all string Id values are present in Inventories of each SearchResult e.g.
Given a string[] list = { "123", "234", "345" } confirm all list values are present at least once in the array of Inventory elements. I'm curious if I can clean this up using one LINQ statement.
SearchResult
--
Inventory[] Inventories
Inventory
--
String Id
Right now, I'm splitting list e.g.
list.Split(').ToDictionary(i => i.ToString(), i => false)
And iterating the dictionary, testing each Inventory. Then, I create a new List<SearchResult> and add items if there are no false values left in the dictionary. This feels clunky.
Code
// instock: IEnumerable<SearchResult>
foreach (var result in instock)
{
Dictionary<string, bool> ids = list.Split(',').ToDictionary(i => i.ToString(), i => false);
foreach (var id in ids)
if (result.Inventory.Any(i => i.Id == id.Key))
ids[id.Key] = true;
if (!ids.Any(i => i.Value == false))
// instockFiltered: List<SearchResult>
instockFiltered.Add(result);
}
Here is a bit of code I wrote. The advantage here is that it uses a hash map, so it has theoretically linear complexity.
public static bool ContainsAll<T>(this IEnumerable<T> superset, IEnumerable<T> subset, IEqualityComparer<T> comparer)
{
var set = new HashSet<T>(superset, comparer);
return set.IsSupersetOf(subset);
}
This bit of LINQ will iterate over the entire stock and then interrogate the inventory (if it's not null) and find inventory that contain one of the values in your list.
var matches = instock.Where(stock => stock.Inventory != null && stock.Inventory.All(i => list.Contains(i.Id));