LINQ: How to declare IEnumerable[AnonymousType]?

后端 未结 6 1838
被撕碎了的回忆
被撕碎了的回忆 2021-02-02 09:34

This is my function:

    private IEnumerable SeachItem(int[] ItemIds)
    {
        using (var reader = File.OpenText(Application.StartupPath + @\"         


        
6条回答
  •  暖寄归人
    2021-02-02 09:51

    The method signature on SearchItem indicates that the method returns an IEnumerable but the anonymous type declared in your LINQ query is not of type string. If you want to keep the same method signature, you have to change your query to only select strings. e.g.

    return myLine.Select(a => a.Text);
    

    If you insist on returning the data selected by your query, you can return an IEnumerable if you replace your return statement with

    return myLine.Cast();
    
    
    

    Then you can consume the objects using reflection.

    But really, if your going to be consuming an anonymous type outside the method that it is declared in, you should define a class an have the method return an IEnumerable of that class. Anonymous types are convenience but they are subject to abuse.

    提交回复
    热议问题