Define a property of an item in a list based on items in another list


Attention all list / LINQ lovers, I have a small challenge for you.

I have two list:

List<ObjectInfo> firstListObject;
List<ObjectInfo> secondListObject;

The first list is a list that I use to manage data. The second list I use to add items as the process goes on. So, from times to times, I will add / remove items on my list.

I have these fields:

public int m_ObjectID { get;set; }
public bool m_IsSelected { get;set; }

And my intention is that each time I "update" my secondListObject, I need to scroll through all the firstListObject to set the m_IsSelected value to true. ELSE the value must be false, meaning that if an item lands in the list the first time, then is removed afterward, the item's m_IsSelected goes false.

Can anyone help me out? Thanks!


Here's what I have done so far:

foreach (var singleOrDefault in secondListObject
    .Select(objectInfo => firstListObject
        .SingleOrDefault(_item => _item.m_ObjectID == inventoryInfo.m_ObjectID))
    .Where(singleOrDefault => singleOrDefault != null))
        .m_IsSelected = true;

Well, in a way, this works. It sets the item I am looking for to true. By default, all m_IsSelected value are false.

But if I remove the item, the m_IsSelected remains true, and that's what I need to do.

So, in a sentence: I need to make a loop in the firstListObject and check if there's any "occurrence" (based on the ID) of each of item of the secondListObject. If that's true, I'll switch the m_IsSelected to true. I just need to make sure that else the m_IsSelected is false, which I do not know how to do...

You could first set everything to false and then just set the one that you want to true:

firstListObject.ForEach(o => o.m_IsSelected = false);
// your foreach goes here