LINQ with IList <selecteditemlist> Issue </selecteditemlist>

时间:2012-07-04 11:18:42

标签: c# linq

我有一个数据表,我需要将每一行转换为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中获得的数据如下所示: -

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

我需要使用LINQ来获取DISTINCT值。

我尝试过简单地使用: -

_area.Distinct();

但是我留下了32个以我开始的条目???

3 个答案:

答案 0 :(得分:5)

您是否尝试过此_area = _area.Distinct();

答案 1 :(得分:2)

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

这将为您提供区域的明确值......

这样怎么样

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

你能更好地解释什么是Distinct,也许你应该重写Equals和GetHashCode,那样它会工作Distinct,就像这样

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;    
    }
}

然后这将按预期工作(希望如此)

_area.Distinct();

答案 2 :(得分:2)

Distinct()方法采用IEqualityComparer<T>类型的paremter,因此在这种情况下,您可以创建一个相等比较器,比较两个SelectListItems的两个值,如下所示:

public class SelectListItemComparer : IEqualityComparer<SelectListItem>
{
    public static SelectListItemComparer Instance = new SelectListItemComparer();
    private SelectListItemComparer() {}
    public bool Equals(SelectListItem x, SelectListItem y)
    {
        return x.Value.Equals(y.Value);
    }

    public int GetHashCode(SelectListItem obj)
    {
        return obj.Value.GetHashCode();
    }
}

然后你可以像这样使用它:

var items = new[]
                {
                    new SelectListItem {Text = "OMC", Value = "OMC"},
                    new SelectListItem {Text = "OMC", Value = "OMC"},
                    new SelectListItem {Text = "OMC", Value = "OMC"},
                    new SelectListItem {Text = "SIAM", Value = "SIAM"},
                    new SelectListItem {Text = "SIAM", Value = "SIAM"},
                    new SelectListItem {Text = "SIAM", Value = "SIAM"},
                    new SelectListItem {Text = "SIAM", Value = "SIAM"},
                    new SelectListItem {Text = "SIAM", Value = "SIAM"}
                };

var comparer = new SelectListItemComparer();
var t1 = items.Distinct(SelectListItemComparer.Instance).ToList();

t1现在只包含两个元素。