Search code examples
c#json.netlinq

How do you return a list<string> from a strong c# object where any items in the object's property contains the specified string


I have 2 objects

public class Root
{
    public Value value { get; set; }
}

public class Value
{
    public List<string> names { get; set; }
}

I have a json string

{
 "value": {
  "names": [
   "MINChanges_231101123225.xls",
   "MultiTierContractTemplate.xlsx"
           ]
          }
}

I deserialize

Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonString);

I want to return a list string where any names contain my specified string

I know how to use the Contains function, as shown below, but how do I use Linq to return me a new list string where any name contains my specified string

myDeserializedClass.value.names.Any(str => str.Contains(mySpecifiedString))

Solution

  • I want to return a list string from downloadedFilesNames where any items in downloadedFilesNames contain my specified string

    Why you use myDeserializedClass.value.names.Any if you actually want Where? You don't want to know if there is at least one matching but you want to find them, so filter the list:

    List<string> filterFileNames = myDeserializedClass.value.names
        .Where(fn => fn.Contains(mySpecifiedString))
        .ToList();