开发者

Mutually exclude property in LINQ

I have a list on which there is a "Active" property that I would li开发者_C百科ke to set to 1 only to an item and to 0 to all other items.

Which is the smartest way to do it in Linq? I know I could set to 0 to all items then 1 only to current, but I was asking if there is a better way to do it.


I'm not sure that LINQ is particularly useful here... how about:

foreach (var item in list)
{
    item.Active = (item == desiredActiveItem ? 1 : 0);
}


I agree with Jon, but if you want to use LINQ anyway, you could do something like this:

list = list.Select(i => { i.Active = (i == desiredActiveItem ? 1 : 0); 
                          return i; }).ToList();

This shows that it really is a good idea to not use LINQ here.


As a pair to Daniel's response, if you must use linq, that's just a perversion. At least just use it to find the item and then act on it.

var item = list.FirstOrDefault**(i => i == desired);

if (item != null)
{
    item.Active = true;
}

** Possible change to First, Single or SingleOrDefault depending on the nature of the list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜