LINQ: How to declare IEnumerable[AnonymousType]?

后端 未结 6 1841
被撕碎了的回忆
被撕碎了的回忆 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 10:09

    Your function is trying to return IEnumerable, when the LINQ statement you are executing is actually returning an IEnumerable where T is a compile-time generated type. Anonymous types are not always anonymous, as they take on a specific, concrete type after the code is compiled.

    Anonymous types, however, since they are ephemeral until compiled, can only be used within the scope they are created in. To support your needs in the example you provided, I would say the simplest solution is to create a simple entity that stores the results of your query:

    public class SearchItemResult
    {
        public string Text { get; set; }
        public int ItemId { get; set; }
        public string Path { get; set; }
    }
    
    public IEnumerable SearchItem(int[] itemIds)
    {
        // ...
        IEnumerable results = from ... select new SearchItemResult { ... }
    }
    

    However, if your ultimate goal is not to retrieve some kind of object, and you are only interested in, say, the Path...then you can still generate an IEnumerable:

    IEnumerable lines = from ... select m.Groups[2].Value;
    

    I hope that helps clarify your understanding of LINQ, enumerables, and anonymous types. :)

提交回复
热议问题