2

我有以下classlinq我用来填充的查询grid

返回的Title每一行都是相同的。我想要做的是mStringdistinct 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

4 回答 4

5
var titleList = mNewItems.Select(i => i.Title).Distinct().ToList();
于 2013-05-15T18:30:32.117 回答
5

将我的评论转换为答案:

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

于 2013-05-15T18:31:53.000 回答
3

还有一个名为moreLinq https://code.google.com/p/morelinq/distinctby 的附加库,您可以根据给定的键进行区分。

就这么简单

   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();
于 2013-05-15T18:31:33.590 回答
2

您可以为不同的实现自定义比较器:

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);
于 2013-05-15T18:46:09.587 回答