Any function of Generic List of Anonymous

prasahant pathak 1 Reputation point
2021-01-11T16:45:48.337+00:00

Hey folks ,

I need to do this but List is not considering the Anonymous type !! any idea how i can do this ?

List<object> foo = new List<object>();
var bar = new { coder= "",designer=""};

if(foo.Any(v=>v.coder==bar.coder)==false)

{foo.Add(bar); }

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,457 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Mike Bowen 1,436 Reputation points Microsoft Employee
    2021-01-12T19:03:00.577+00:00

    Hi, I'm not part of the dotnet-csharp team, but I know a bit about C#, so I can explain the issue here. There are 2 issues with your code.

    The reason .Add isn't recognized is because you need to add "using System.Linq;" at the top of your file.

    To get a string value from a dynamic object the syntax is: (string)v.GetType().GetProperty("coder").GetValue(v, null)

    A working example of a console app with this code would look like this:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    namespace Foo
    {
        class Program
        {
            public static void Main(string[] args)
            {
                AddFoo();
            }
    
            public static void AddFoo()
            {
                List<object> foo = new List<object>();
                dynamic bar = new { coder = "", designer = "" };
    
    
    
                if (foo.Any(v => (string)v.GetType().GetProperty("coder").GetValue(v, null) == bar.coder) == false)
    
                {
                    foo.Add(bar);
                }
            }
        }
    }
    
    0 comments No comments