Zhrez Pain
Zhrez Pain

Reputation: 339

How to check all values in List of Class are same or not?

I need help to write a function or logic to find if all values in my List of type class (named Stack) are equal or not. So it will return either true or false.

public class Stack
{
    public string Key         { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate   { get; set; }
}

I have created a class with 3 properties as above.

List<Stack> Stack = new List<Stack>();
Stack WOKey = new Stack() { Key = Resource, StartDate = WorkOrderST, EndDate = WorkOrderED };
Stack.Add(WOKey);

I have created 2 objects with StartDate and EndDate assigned to them through variables.

So I need a logic or function that will return true, if all StartDate have all same values (eg DateTime(2018, 1, 1)) and as case for EndDate (eg DateTime (2018, 1, 30)).

Should I use foreach or is it possible with LINQ? I am new to C# so I am not sure how to implement it.

Upvotes: 1

Views: 346

Answers (2)

Matthiee
Matthiee

Reputation: 493

I would use Linq

You can can do the following:

Don't forget to import using System.Linq;

List<Stack> Unavailability = new List<Stack>
{
        new Stack{  Key = "A", StartDate = new DateTime(2018,1,1), EndDate = new DateTime(2018,1,30) },
        new Stack{  Key = "B", StartDate = new DateTime(2018,1,1), EndDate = new DateTime(2018,1,30)},
        new Stack{  Key = "C", StartDate = new DateTime(2018,1,1), EndDate = new DateTime(2018,1,30)}
};

bool allUnique = Unavailability.Select(_ => new { _.StartDate, _.EndDate }).Distinct().Count() <= 0;

What I did here was project the Stack list using the Select to a anonymous type with the objects in it that you want to compare. Now we can use the Distinct operator to determin all the distinct values.

If the result is less than or equal to 0 that means all the values are unique and if it is something else that means multiple unique values were found.

Upvotes: 3

Ron Beyer
Ron Beyer

Reputation: 11273

This is pretty simple with LINQ:

bool allSame = Unavailability.All(s => s.StartDate == new DateTime(2018, 1, 1) &&
                                       s.EndDate == new DateTime(2018, 1, 30));

The .All returns true if every item in the sequence satisfies the condition. See .NET Enumerable.All.

If you want to see if they are all equal, just use the first value...

bool allSame = Unavailability.All(s => s.StartDate == Unavailability[0].StartDate &&
                                       s.EndDate == Unavailability[0].EndDate);

Upvotes: 6

Related Questions