linq不同的查询?

时间:2013-03-22 14:56:57

标签: linq

我需要Linq的一点帮助我有一个带有restourants表的数据库表。在DB我有“TableNumber,Floor,RestaurantID”我想获得所有楼层的列表。例如,如果我有这个清单:

TableNumber, Floor , RestaurantID
10             1          1  
11             1          1     
12             2          1     
13             2          1     
14             3          1     

我想只获得“1,2,3”。

现在该方法返回所有行。

        public IEnumerable<ListPad.Item> GetFloorsListPads(SSF.ART.Key restaurant_id)
    {
        return from restaurant_floor in EnterpriseTouchRestaurantApplication.TouchRestaurant.AllRestaurantTables
                where restaurant_floor.RestaurantID == restaurant_id && restaurant_floor.Active == true
                orderby restaurant_floor.Floor
                select new ListPad.Item()
                {
                    Color = Color.SkyBlue,
                    Text = string.Format("{0}", restaurant_floor.Floor),
                    Tag = restaurant_floor
                };
    }

提前感谢所有帮助。

1 个答案:

答案 0 :(得分:1)

您需要一两件事,具体取决于ListPad.Item是否以您描述的方式定义相等(通过覆盖EqualsGetHashCode)。如果是这样,那么在您的查询中添加.Distinct()将为您提供不同的项目。如果没有,你可以采用以下三种方式之一。

  1. 返回一个匿名类型,在其上调用Distinct,并映射到实际类型(懒惰方式)
  2. IEquatable上实施ListPad.Item,覆盖EqualsGetHashCode(您需要研究如何正确实施GetHashCode,以使其符合您的平等条件)
  3. 定义一个定义您的平等的IEqualityComparer<ListPad.Item>
  4. 1是懒惰的方式,但编码较少。如果您的条件为ListPad.Item的所有使用(不仅仅是这个特定场景)定义了相等,那么2很方便。 3将等式检查与实际类型分开,如果您有其他的情况,其中等式的定义不同,这是很方便的。