简体   繁体   中英

Setting 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!

EDIT

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))
{
    singleOrDefault
        .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

So It greatly depends on what you are doing before this point. If you had the firsListObject created without modifying it at all. Then the o.m_IsSelected of all the objects of the list will be in "false" because that is the default initialization value for booleans, unless you set them to something different.

Then you would only need to update the objects that have to be set to true.

If you have updated the list and modified what is selected and what not and you need to refresh. Then Kenneth option is good, then you could again just do your code after initializing all the values.

And you have a third option you want to update all the items in one shot. You could do:

foreach (var item in secondListObject)
{
    item.m_IsSelected = firstListObject.Any(x => x.m_ObjectID == item.m_ObjectID);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM