具有IList< SelectedItemList>的LINQ;问题 [英] LINQ with IList<SelectedItemList> Issue

查看:61
本文介绍了具有IList< SelectedItemList>的LINQ;问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据表,我需要在其中将每一行转换为一个IList

I have a Datatable in which i need to convert each row into a IList

public IList<SelectListItem> _area = new List<SelectListItem>();
public IList<SelectListItem> _team = new List<SelectListItem>();

     foreach (DataRow row in dt.Rows)
            {
       _area.Add(new SelectListItem() { Text = row[1].ToString(), Value = row[1].ToString() });
       _team.Add(new SelectListItem() { Text = row[0].ToString(), Value = row[0].ToString() });

            }

然后在_area中获得的数据如下所示:-

The data that is then obtained in _area looks like this :-

Text                     Value
OMC                      OMC
OMC                      OMC
OMC                      OMC
SIAM                     SIAM
SIAM                     SIAM
SIAM                     SIAM                     
SIAM                     SIAM                     
SIAM                     SIAM

我需要使用LINQ来获得DISTINCT值.

I need to use LINQ to get the DISTINCT Values.

我尝试仅使用:-

_area.Distinct();

但是我只剩下32个开始的条目了?

But i'm left with 32 entries that i started with???

推荐答案

_area.GroupBy(x => x.Value).Select(x => x.Key);

这将为您提供区域的独特价值...

This will give you the distinct values of the areas...

这样怎么样

_area.GroupBy(x => x.Value).Select(x => x.First());

您能更好地解释什么是Distinct,也许您应该重写Equals和GetHashCode,那样它将使Distinct有效,就像这样

Can you explain better what is Distinct, maybe you should override Equals and GetHashCode and that way It will work the Distinct, something like this

class Foo
{
    public string Text { get; set; }
    public string Value { get; set; }

    public override bool Equals(object obj)
    {
        var foo = obj as Foo;
        if(foo == null) return false;

        return foo.Text == Text && foo.Value == Value;
    }

    public override int GetHashCode()
    {
        return Text.GetHashCode() * Value.GetHashCode() ^ 7;    
    }
}

然后它将按您期望的那样工作(希望如此)

and then this will work as you expect (hope so)

_area.Distinct();

这篇关于具有IList&lt; SelectedItemList&gt;的LINQ;问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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