比较几个对象并检查是否具有相同的值

时间:2019-05-11 12:31:29

标签: c#

我想知道镜头是否不重复或用户没有给出相同的值。

这是我的机票舱位:

   public class TicketBl
    {
        public int Id { get; set; }
        public string UserEmail { get; set; }
        public int CinemaId { get; set; }
        public int MovieId { get; set; }
        public int CinemaHallId { get; set; }
        public string Row { get; set; }
        public int Seat { get; set; }
        public DateTime TimeOfSeance { get; set; }
        public int Price { get; set; }
    }

我有门票清单:

var tickets = new List<TicketBl>
            {
                new TicketBl()
                {
                    CinemaHallId = 1, MovieId = 1, Row = "A", Seat = 1, CinemaId = 1,
                    TimeOfSeance = new DateTime(2019, 05, 06), UserEmail = "bk@gmail.com"
                },
                new TicketBl()
                {
                    CinemaHallId = 1, MovieId = 1, Row = "A", Seat = 2, CinemaId = 1,
                    TimeOfSeance = new DateTime(2019, 05, 06), UserEmail = "bk@gmail.com@gmail.com"
                },
                new TicketBl()
                {
                    CinemaHallId = 1, MovieId = 1, Row = "A", Seat = 1, CinemaId = 1,
                    TimeOfSeance = new DateTime(2019, 05, 06), UserEmail = "bk@gmail.com@gmail.com"
                }
            };

我创建了一些值比较器类,但是它不起作用。等于不利于比较器值?如何检查对象中的值相同。

public static class ValuesComparer
    {
        public static bool CheckListHasSameValues<T>(List<T> values)
        {
if (values.Count() == 1)
            {
                return false;
            }

            for (int i = 0; i < values.Count - 1; i++)
            {
                for (int j = i + 1; j < values.Count; j++)
                {
                    if (values[i].Equals(values[j]))
                    {
                        return true;
                    }
                }
            }

            return false;
        }
    }

1 个答案:

答案 0 :(得分:0)

比较不会比较不同类型的项目,例如字符串和整数。使用IEqual:

    public class Ticket : IEquatable<Ticket>
    {
        public int Id { get; set; }
        public string UserEmail { get; set; }
        public int CinemaId { get; set; }
        public int MovieId { get; set; }
        public int CinemaHallId { get; set; }
        public string Row { get; set; }
        public int Seat { get; set; }
        public DateTime TimeOfSeance { get; set; }
        public int Price { get; set; }

        public Boolean Equals(Ticket other)
        {
            return
                (this.Id == other.Id) &&
                (this.CinemaId == other.CinemaId) &&
                (this.MovieId == other.MovieId) &&
                (this.CinemaHallId == other.CinemaHallId) &&
                (this.Row == other.Row) &&
                (this.Seat == other.Seat) &&
                (this.TimeOfSeance == other.TimeOfSeance);

        }
    }