0

Hi I want to search class from dictionary through LINQ

My data form is below. And i wanna use SearchDataFromString method in HoldingData class

When inserting a string, Linq is used to return all data of the symbol or name containing the string in the form of List.

public class HoldingData {
public Dictionary<string, SymbolsList> data;

public List<SymbolsList> SearchDataFromString(string nameOrSymbol){

//All data is store in **data**
//use LINQ
}
}



[System.Serializable]
public class SymbolsList
{
    public string symbol;
    public string name;
    public string exchange;
}

Someone help me my problem thanks.

Natejin
  • 55
  • 9

2 Answers2

2

You can use

data.Where( x => x.Value.symbol.Contains("#{YOURSTRING}") )

to find the element which SymbolsList.symbol contains #{YourString}

it also work with name if you use

data.Where( x => x.Value.name.Contains("#{YOURSTRING}") )

or if you wish to check if one of them contains that, try to make a method in SymbolsList like this

public bool ContainsString(String arg) {
    return name.Contains(arg) || symbol.Contains(arg);
}

then use linq like this

data.Where( x => x.Value.ContainsString("#{YOURSTRING}") )
Arphile
  • 841
  • 6
  • 18
2

You may use:

return data.Values.Where(x => x.symbol.Contains(nameOrSymbol)
                         || x.name.Contains(nameOrSymbol)).ToList();
  • This is really good code and simple. But i want to search regardless of case. Do you have good idea about it? – Natejin Jul 06 '20 at 01:47
  • @Natejin Either use [`IndexOf()`](https://learn.microsoft.com/en-us/dotnet/api/system.string.indexof#System_String_IndexOf_System_String_System_StringComparison_) instead of `Contains()` or create a [`ContainsIgnoreCase` extension method](https://stackoverflow.com/a/54686459/8967612) to make it more readable. Alternatively, you may use `x.symbol.ToLower().Contains(nameOrSymbol.ToLower())` but that's not a good idea if you're dealing with Unicode strings. – 41686d6564 stands w. Palestine Jul 06 '20 at 02:01