0

I have a list of tickets. Each ticket belongs to a single event. I want create a list of all events from tickets. I can get this list, but the same event (value) is repeated in the list. How can I ensure that an event is only added the list once?

 List<int> tickets = new List<int>();

 List<Event> events = new List<Event>();

 foreach (var s in tickets)
 {
     events.Add(_context.Event.Find(s));
 }
4

3 回答 3

8

如果事件的顺序不重要,您可以使用HashSet<Event>List 来代替。如果事件已经存在于哈希集中,则不会再次添加事件。还要确保 Event 已经覆盖了比较事件实际属性的 Equals 和 GetHashCode 方法。

于 2013-04-22T16:15:23.550 回答
2

完整的 Linq 解决方案Distinct()

var events = tickets.Select(ticket => _context.Event.Find(ticket)).Distinct();
于 2013-04-22T16:18:01.837 回答
2

您是否尝试过使用该List<T>.Contains()方法?

foreach (var s in tickets)
{
    var event = _context.Event.Find(s);
    if (!events.Contains(event))
    {
        events.Add(event);
    }
}
于 2013-04-22T16:15:30.887 回答