Linq查询的独特价值

时间:2013-05-15 18:26:32

标签: c# wpf

我使用以下classlinq查询来填充grid

Title对于返回的每一行都是相同的。我要做的是使用查询中的mString distinct填充Title,以便将其绑定到单独的文本块。

我可能不需要显示所有代码,但也许它会有所帮助。如何显示distinct Title

public class Items
{
    public int Id { get; set; }
    public string Details { get; set; }
    public string Title { get; set; }
    public int NewNumber { get; set; }
}

private ObservableCollection<Items>  mItem = new ObservableCollection<Items>();
private string mString = string.Empty;

public string SpecTitle
{
    get { return mString; }
}

public ObservableCollection<Items> GetItems
{
    get { return mItem; }
}

这是linq查询

var results = (from z in mContext.View
               orderby z.ItemNumber ascending
               where z.ItemId == mId
               select new Items()
               {                                         
                   Id = z.ItemId,
                   Details = z.Details,
                   Title = z.ItemTitle,
                   NewNumber = z.ItemNumber
               });

List<Items> mNewItems = results.ToList();
mItem.Clear();
mNewItems.ForEach(y => mItem.Add(y));

4 个答案:

答案 0 :(得分:5)

将我的评论转换为答案:

只做Items.Select(x => x.Title).Distinct();

答案 1 :(得分:4)

var titleList = mNewItems.Select(i => i.Title).Distinct().ToList();

答案 2 :(得分:2)

还有一个名为moreLinq https://code.google.com/p/morelinq/的额外库,其扩展名不同,您可以根据给定的密钥进行区分。

它就像这个

一样
   var results = (from z in mContext.View
                                 orderby z.ItemNumber ascending
                                 where z.ItemId == mId
                                 select new Items()
                                 {                                         
                                     Id = z.ItemId,
                                     Details = z.Details,
                                     Title = z.ItemTitle,
                                     NewNumber = z.ItemNumber

                                 }).DistinctBy(c=>c.Title).ToList();

答案 3 :(得分:1)

您可以为distinct:

实现自定义比较器
public class ItemsComparer : IEqualityComparer<Items>
{
    public bool Equals(Items x, Items y)
    {
        return x.Title == y.Title;
    }

    public int GetHashCode(Items obj)
    {
        return obj.Title.GetHashCode();
    }
}

然后只需使用

var titleList = mNewItems.Distinct(new ItemsComparer()).Select(t=>t.Items);