简体   繁体   中英

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. How do i this?

Thanks

You could use Distinct :

return gridValues.Distinct().ToList()

A more efficient approach is using a 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. 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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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