Home > Software engineering >  Translate List into List of Int
Translate List into List of Int

Time:11-02

I have a json value as below

"BookShops": [
    {
        "Name": "Modern",
        "BookID": [
            "101"
        ]
    },
    {
        "Name": "Windshore",
        "BookID": [
            "102"
        ]
    },
    {
        "Name": "Winter",
        "BookID": [
            "105"
        ]
    },
]

Each of element of bookshops have only one bookID (even their type is int array) I want to move bookID into List Of Int just like the expect result

"GlobalBookID":[101,102,105]

that define in class as

List<int> GlobalBookIDs

Can I know to translate it in single line ?

CodePudding user response:

You can use LINQ to select the BookID integers.

var bookIds = bookshops.Select(b => b.BookID[0]);

However, why is the BookID an array of integers anyway?

CodePudding user response:

If multiple ids are possible (you have an array of for BookID) you can try SelectMany:

List<int> GlobalBookIDs = bookshops
  .SelectMany(shop => shop.BookID)
  .Select(id => Convert.ToInt32(id)) // you have ids being strings in your JSON
  // .Distinct() // uncomment if you want to get distinct BookIds
  .ToList();
  • Related