简体   繁体   English

从列表中选择不同的值

[英]Selecting Distinct Values from a List

Here is my code for my list: 这是我的清单代码:

    public static List<Int32> getValueFilterItems()
    {            
        List<Int32> gridValues = new List<Int32>();

        ASPxGridView gridViewPromo = (ASPxGridView)gridViewPromo.GetRowValues(4, "Value");

        int val = Convert.ToInt32(gridViewPromo);

        gridValues.Add(val);

        return gridValues;
    }

I want to return only DISTINCT values from the list as there many repetitive values. 我想只从列表中返回DISTINCT值,因为有很多重复的值。 How do i this? 我该怎么办?

Thanks 谢谢

You could use Distinct : 您可以使用Distinct

return gridValues.Distinct().ToList()

A more efficient approach is using a HashSet<Int32> : 一种更有效的方法是使用HashSet<Int32>

public static List<Int32> getValueFilterItems()
{            
    HashSet<Int32> values = new HashSet<Int32>();

    ASPxGridView gridViewPromo = (ASPxGridView)gridViewPromo.GetRowValues(4, "Value");

    int val = Convert.ToInt32(gridViewPromo);
    values.Add(val);
    return values.ToList();
}

Edit : You're also using gridViewPromo even if it's unitialized. 编辑 :您还使用gridViewPromo即使它未初始化。 You have to initialize it before you use it: 您必须先对其进行初始化,然后才能使用它:

ASPxGridView gridViewPromo = (ASPxGridView) whateverYourGridIs;
int val = Convert.ToInt32(gridViewPromo.GetRowValues(4, "Value"));

Final note: why do you need a collection anyway if you select a single value? 最后说明:如果选择单个值,为什么仍然需要收集?

Simple way is to use: 简单的方法是使用:

 return gridValues.Distinct().ToList();

Although HashSet will not need either Distinct. 尽管HashSet不需要两者都不同。

Your function does not return more than one value in the list , I suppose you are calling this function from outside something like this 您的函数不会在列表中返回多个值,我想您是从类似这样的外部调用此函数的

HashSet<Int32> values = new HashSet<Int32>();
var value1 = getValueFilterItems(4, "Value");
var value2 = getValueFilterItems(5, "Value");

//HashSet returns true from Add method if element added, returns false if element already exists
values.Add(value1);
values.Add(value2);

Modified function should be with HashSet 修改后的功能应与HashSet一起使用

public static Int32 getValueFilterItems(int visibleIndex, string fieldNames)
{            
    ASPxGridView gridViewPromo = (ASPxGridView)gridViewPromo.GetRowValues(visibleIndex,fieldNames);
    return Convert.ToInt32(gridViewPromo);
}

将返回值更改为
return gridValues.Distinct.ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM