1

I'm implementing simple search engine.all the data saved as a JSON in text file. My implementing scenario is,If I search word like 'rock' method should return result as list of tag Id's containing 'rock' value.I have been looking for sample codes but in every exsample they search by tag like track_id" but I need search by value. This is my sample JSON array ..

enter image description here

Test word : rock expected result : 991335,991336,991337

1 Answer 1

2

I suggest to use a JSON library, like Json.net.

If you can allow to read the whole file, its super-easy with linq.

class TrackElement {
    public Track Track {get;set;}
}
class Track {
    public string track_id{get;set;}
    public string track_name{get;set;}
    public string track_category{get;set;}
}

Read file, deserialize and search:

var data = File.ReadAlltext("path/to/your/file.txt");
List<TrackElement> database = JsonConvert.DeserializeObject<List<TrackElement>>(data);

var results = database.Where(i=>i.Track.track_category.ToLower().Contains("rock")).Select(t=>t.Track.track_id);

If the database is real large, you should not read the whole stuff into memory, in this case you can use streamed parsing (token-by-token), reading the file directly. For this, you can use the JsonReader class from Json.net lib. (http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonReader.htm)

Sign up to request clarification or add additional context in comments.

3 Comments

Thanx for your quick response and your answer is correct but it's difficult to adjust to my scenario..Because you used to search only in track_category tag. var results = database.Where(i=>i.Track.track_category.ToLower().Contains("rock")).Select(t=>t.Track.track_id); but in my case I can't define any fix tag. 'Rock' can be saved as track name,track category or artist name.. I need return track id list which are contain 'Rock' in any tag..
Then the only way to solve is to use a more complex search expression, like: var results = database.Where(i=>i.Track.track_category.ToLower().Contains("rock") || i.Track.track_id.ToLower().Contains("rock") || i.Track.track_name.ToLower().Contains("rock") ).Select(t=>t.Track.track_id); You can make it much more clear if you write a helper method for the search expression.
Great, easy and fast solution! There's a typo in the code, ReadAllText with capital T.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.