Kevin
Kevin

Reputation: 97

IList<T> return as a generic

I'm a beginner for coding ,and I was trying to create a search engine , but there s a part I dont know how to solve it that returns an IList as a generic,

public IList<T> Search<T>(string textSearch)
{

    IList<T> list = new List<T>();

    var result = new DataTable();
    using (Analyzer analyzer = new PanGuAnalyzer())
    {
        var queryParser = new QueryParser(Version.LUCENE_30, "FullText", analyzer);

        queryParser.AllowLeadingWildcard = true;

        var query = queryParser.Parse(textSearch);

        var collector = TopScoreDocCollector.Create(1000, true);

        Searcher.Search(query, collector);

        var matches = collector.TopDocs().ScoreDocs;


        result.Columns.Add("Title");
        result.Columns.Add("Starring");
        result.Columns.Add("ID");

        foreach (var item in matches)
        {
            var id = item.Doc;
            var doc = Searcher.Doc(id);

            var row = result.NewRow();

            row["Title"] = doc.GetField("Title").StringValue;
            row["Starring"] = doc.GetField("Starring").StringValue;

            row["ID"] = doc.GetField("ID").StringValue;

            result.Rows.Add(row);

        }
    }
    return result;
}

but in this code , I couldn't return result ,it says Cannot Implicitly convert type 'Data.DataTable' to 'Generic.IList',An explicit conversion exists.so how can I solve this?

Upvotes: 2

Views: 462

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460038

I guess you don't want to support generics since it doesn't make sense and is impossible. You have a class, for example Film, then return a List<Film>, you don't need the DataTable:

public IList<Film> SearchFilms(string textSearch)
{
    IList<Film> list = new List<Film>();
    using (Analyzer analyzer = new PanGuAnalyzer())
    {
        var queryParser = new QueryParser(Version.LUCENE_30, "FullText", analyzer);
        queryParser.AllowLeadingWildcard = true;
        var query = queryParser.Parse(textSearch);
        var collector = TopScoreDocCollector.Create(1000, true);

        Searcher.Search(query, collector);
        var matches = collector.TopDocs().ScoreDocs;

        foreach (var item in matches)
        {
            var film = new Film();

            var id = item.Doc;
            var doc = Searcher.Doc(id);

            film.Title = doc.GetField("Title").StringValue;
            film.Starring = doc.GetField("Starring").StringValue;
            film.ID = doc.GetField("ID").StringValue;

            list.Add(film);
        }
    }
    return list;
}

Upvotes: 1

Imad
Imad

Reputation: 7490

Your return statement should be

result.AsEnumerable().ToList();

Don't forget to add namespace

using System.Linq;

Upvotes: 0

Related Questions