Question

Let's say I have the following class.

class Wedding
{
    public DateTime When { get; set; }
    public string Where { get; set; }
}

And I have a list of this kind of elements.

List<Wedding> weddings = GetWeddings(...);

So from somewhere we got a list.

For this I would like to use a method that can easily tell me if a wedding at a certain datetime is in the list or not (bool). Like:

public bool WeddingInList(List<Weddings> list, DateTime dateTime)
{
    return list.Contains(...)
}

I'm not very familiar with Linq and Func...

Any help is appreciated, thank you.

Était-ce utile?

La solution

DateTime check;

bool weddingExistsAtCheckDate = weddings.Any(wedding => wedding.When == check);

Clarification:

The Any method takes a Func<T, bool> for T being the class that is in the container.

Assuming you had a function

bool SomeFunc(Wedding wedding) { return wedding.When == check }

you could have passed that:

bool weddingExistsAtCheckDate = weddings.Any(SomeFunc);

However, then you'd have to get check in there somehow. Anyway, the function above can be shortened to :

bool weddingExistsAtCheckDate = weddings.Any((Wedding wedding) => { return wedding.When == check });

Which can again be shortened to:

bool weddingExistsAtCheckDate = weddings.Any(wedding => wedding.When == check);

because all the other syntax was something that the compiler already knew anyway... anything else and it would have complained.

The resulting short version is called a lambda expression.

Autres conseils

In addition to nvoigt answer, you said you want it in a method. You can use an extension method so you don't have to use a lambda expression every time:

Declare this class somewhere outside in the same namespace

public static class extension
{
    public static bool IsInWeddingList(this IEnumerable<Wedding> weds, DateTime check)
    {
       return weds.Any(wedding => wedding.When == check);
    }
}

and call it's method on your weddings list like this:

       List<Wedding> weddings = GetWeddings(...);
       DateTime check=DateTime.Now; //some date
       bool result=weddings.IsInWeddingList(check);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top