简体   繁体   中英

How to update value in anonymous list in c#

I have a list which is anonymous type and I've tagId, isTagSelected & tagName in it. What I want is want to add 4th property based on some condition

Code:

var tagDetails = tagIdList.Select((x, i) => new { tagId = x, isTagSelected = tagSelectionList[i], tagName = tagList[i] }).ToList();

Result:

{tagId = 1, isTagSelected = true, tagName = "a"}
{tagId = 2, isTagSelected = false, tagName = "b"}
{tagId = 3, isTagSelected = true, tagName = "c"}

What I want is, if tagName is a then add Size = "S" else string.empty or null . How can I achieve this? I tried following approach which is, add Size in all of them and then remove from unwanted place but it is not working.

Code:

var tagDetails = tagIdList.Select((x, i) => new { tagId = x, isTagSelected = tagSelectionList[i], tagName = tagList[i], itemSize = itemSize }).ToList();

Result:

{tagId = 1, isTagSelected = true, tagName = "a", Size = "S"}
{tagId = 2, isTagSelected = false, tagName = "b", Size = "S"}
{tagId = 3, isTagSelected = true, tagName = "c", Size = "S"}

I tried foreach loop but I can change read only property. Is there anyway that I can remove Size from "b" & "c"?

Expected Result:

{tagId = 1, isTagSelected = true, tagName = "a", Size = "S"}
{tagId = 2, isTagSelected = false, tagName = "b", Size = "" or null}
{tagId = 3, isTagSelected = true, tagName = "c", Size = "" or null}

Im not at a VS instance but it seems like this would work.

var tagDetails = tagIdList.Select((x, i) => new 
        { tagId = x,
          isTagSelected = tagSelectionList[i], 
          tagName = tagList[i], 
          Size = tagList[i] == "a" ? "S" : null 
    }).ToList();

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