Linq-如何在查询中使用函数 [英] Linq - how can I use a function in a query

查看:67
本文介绍了Linq-如何在查询中使用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在WP7(芒果)上使用C#.我尝试使用特殊查询,因为收到错误:

I use C# on WP7 (Mango). I try to use a special query because I receive an error:

不支持方法'Int32 orderBirthday(System.DateTime)' 转换为SQL.

Method 'Int32 orderBirthday(System.DateTime)' has no supported translation to SQL.

是的,我知道... Linq无法使用我的函数,但我不知道正确的方法...

Yes, I know... Linq can't use my function but I don't know the right way...

我有一个数据库表,其中包含列namebirthday.在我的查询中,我将计算到下一个生日有几天(从所有项目开始),然后以降序"订购.

I have a database table with the columns name and birthday. In my query I will calculate how many days are to the next birthday (from all items) and then I will order with "descending".

static int orderBirthday(DateTime Birthday)
    {
        DateTime today = DateTime.Today;
        DateTime birthday = Birthday;
        DateTime next = new DateTime(today.Year, birthday.Month, birthday.Day);

        if (next < today)
            next = next.AddYears(1);

        int numDays = (next - today).Days;

        // No Conversion
        return numDays;
    }

 public void LoadCollectionsFromDatabase()
    {

        DateTime today = DateTime.Today;

        var toDoItemsInDB = from ToDoItem todo in toDoDB.Items
                            let daysToBirthday = orderBirthday(todo.ItemDate)
                            orderby daysToBirthday ascending
                            select todo;

        // Query the database and load all to-do items.
        AllToDoItems = new ObservableCollection<ToDoItem>(toDoItemsInDB);
.
.
.
}

推荐答案

您要么必须从数据库中提取所有内容,然后对它们进行本地排序(如Enigmativity),要么找到一种方法来表达LINQ语句本身中的排序操作.并且由于将排序行为提取到了它自己的函数中,因此您可能想重用此逻辑.在这种情况下,最好的选择是创建一个过滤IQueryable的函数.

You either have to pull everything from the database and sort it locally (as Enigmativity) shows, or find a way to express the sort operation in a LINQ statement itself. And since you extracted the sorting behavior into its own function, you probably want to reuse this logic. In that case your best bet is to create a function that filters an IQueryable.

以下是如何执行此操作的示例:

Here is an example of how to do this:

public static IOrderedQueryable<Item> OrderByBirthday(
    this IQueryable<Item> items)
{
    return
        from item in items
        let today = DateTime.Today
        let birthday = item.ItemDate
        let next = new DateTime(today.Year, birthday.Month, birthday.Day)
        let next2 = next < today ? next.AddYears(1) : next
        orderby (next - today).Days
        select item;
}

您可以使用以下方法:

var toDoItemsInDB = OrderByBirthday(toDoDB.Items);

或者您可以将其用作扩展方法:

Or you can use it as an extension method:

var toDoItemsInDB = toDoDB.Items.OrderByBirthday();

这篇关于Linq-如何在查询中使用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆