在单个LINQ语句中使用.Select和.Where [英] Using .Select and .Where in a single LINQ statement

查看:225
本文介绍了在单个LINQ语句中使用.Select和.Where的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用LINQ从特定表中收集唯一ID.问题是我还需要一个WHERE语句,该语句应仅根据我已设置的要求过滤结果.与必须大量使用LINQ相对较新,但是我或多或少地使用以下代码:

I need to gather Distinct Id's from a particular table using LINQ. The catch is I also need a WHERE statement that should filter the results based only from the requirements I've set. Relatively new to having to use LINQ so much, but I'm using the following code more or less:

private void WriteStuff(SqlHelper db, EmployeeHelper emp)
{
    String checkFieldChange;
    AnIList tableClass = new AnIList(db, (int)emp.PersonId);
    var linq = tableClass.Items
        .Where(
           x => x.UserId == emp.UserId 
             && x.Date > DateBeforeChanges 
             && x.Date < DateAfterEffective 
             && (
                     (x.Field == Inserted)
                  || (x.Field == Deleted)))
                )
             ).OrderByDescending(x => x.Id);

    if (linq != null)
    {
        foreach (TableClassChanges item in linq)
        {
            AnotherIList payTxn = new AnotherIList(db, item.Id);
            checkFieldChange = GetChangeType(item.FieldName);

            // Other codes that will retrieve data from each item 
            // and write it into a text file
        }
    }
}

我尝试为var linq添加.Distinct,但它仍返回重复的项目(表示具有相同的ID).我已经阅读了很多站点,并尝试将.Select添加到查询中,但是.Where子句代替了.在其他文章中,查询在检索值并将其放在var中的方式有​​所不同.我也尝试使用.GroupBy,但是当使用Id作为键时,出现至少一个对象必须实现IComparable"的问题.

I tried to add .Distinct for var linq but it's still returning duplicate items (meaning having the same Id's). I've read through a lot of sites and have tried adding a .Select into the query but the .Where clause breaks instead. There are other articles where the query is somehow different with the way it retrieves the values and place it in a var. I also tried to use .GroupBy but I get an "At least one object must implement IComparable" when using Id as a key.

该查询实际上有效,并且我能够从具有所需规格的列中输出数据,但是我似乎无法使.Distinct有效(这是真正缺少的唯一内容).我试图创建两个var,其中一个触发不同的调用,然后使用嵌套的foreach来确保值唯一,但是要收集成千上万条记录来收集性能影响实在太多了.

The query actually works and I'm able to output the data from the columns with the specifications I require, but I just can't seem to make .Distinct work (which is the only thing really missing). I tried to create two vars with one triggering a distinct call then have a nested foreach to ensure the values are just unique, but will thousands of records to gather the performance impact is just too much.

我也不确定是否必须重写或使用IEnumerable满足我的要求,并认为我会问这个问题,以防万一有更简单的方法,或者是否可以同时使用.Select和...................

I'm unsure as well if I'd have to override or use IEnumerable for my requirement, and thought I'd ask the question around just in case there's an easier way, or if it's possible to have both .Select and .Where working in just one statement?

推荐答案

为了 Enumerable.Distinct 为您的类型工作,您可以实现IEquatable<T>并为EqualsGetHashCode提供合适的定义,否则它将使用默认实现:比较引用相等性(假设您使用的是引用类型)

In order for Enumerable.Distinct to work for your type, you can implement IEquatable<T> and provide suitable definitions for Equals and GetHashCode, otherwise it will use the default implementation: comparing for reference equality (assuming that you are using a reference type).

从手册中:

Distinct(IEnumerable)方法返回不包含重复值的无序序列.它使用默认的相等比较器Default来比较值.

The Distinct(IEnumerable) method returns an unordered sequence that contains no duplicate values. It uses the default equality comparer, Default, to compare values.

默认的相等比较器Default用于比较实现IEquatable通用接口的类型的值.要比较自定义数据类型,您需要实现此接口并为该类型提供自己的GetHashCode和Equals方法.

The default equality comparer, Default, is used to compare values of the types that implement the IEquatable generic interface. To compare a custom data type, you need to implement this interface and provide your own GetHashCode and Equals methods for the type.

在您的情况下,看起来您可能只需要比较ID,但是您可能还需要比较其他字段,具体取决于两个对象相同"对您的含义.

In your case it looks like you might just need to compare the IDs, but you may also want to compare other fields too depending on what it means for you that two objects are "the same".

您还可以考虑使用 DistinctBy href ="http://code.google.com/p/morelinq/"> morelinq .

请注意,这仅是LINQ to Objects,但我认为这就是您所使用的.

Note that this is LINQ to Objects only, but I assume that's what you are using.

另一种选择是将GroupByFirst组合:

Yet another option is to combine GroupBy and First:

 var query = // your query here...
    .GroupBy(x => x.Id)
    .Select(g => g.First());

例如,这在LINQ to SQL中也将起作用.

This would also work in LINQ to SQL, for example.

这篇关于在单个LINQ语句中使用.Select和.Where的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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