LINQ: How to declare IEnumerable[AnonymousType]?

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

    I am not necessarily recommending this... It is a kind of subversion of the type system but you could do this:

    1) change your method signature to return IEnumerable (the non generic one)

    2) add a cast by example helper:

    public static class Extensions{
        public static IEnumerable CastByExample(
                this IEnumerable sequence, 
                T example) where T: class
        {
            foreach (Object o in sequence)
                yield return o as T;
        }
    }
    

    3) then call the method something like this:

    var example = new { Text = "", ItemId = 0, Path = "" };
    foreach (var x in SeachItem(ids).CastByExample(example))
    {
        // now you can access the properties of x 
        Console.WriteLine("{0},{1},{2}", x.Text, x.ItemId, x.Path);
    }
    

    And you are done.

    The key to this is the fact that if you create an anonymous type with the same order, types and property names in two places the types will be reused. Knowing this you can use generics to avoid reflection.

    Hope this helps Alex

提交回复
热议问题