alonp
alonp

Reputation: 1337

Filter result using linq to return a count of entries by remove duplicates using specific parameter

For example:

The list is list of Users

First entry: User -> Id=111 name=aaa

First entry: User -> Id=123 name=aaa

First entry: User -> Id=124 name=ccc

First entry: User -> Id=125 name=ddd

First entry: User -> Id=126 name=ddd

The result if the param is Id is 5 and if it's name it will be 3 (because there is 3 unique names)

The expected output is the count of Users with provided parameter when this param is distinct.

Thanks in advance

Upvotes: 0

Views: 2326

Answers (5)

ChriPf
ChriPf

Reputation: 2780

For a short and generic way to do it in LINQ I would suggest:

list.GroupBy(user=>user.Id).Count();
list.GroupBy(user=>user.Name).Count();

Of course if you do not need to pass the parameter name as string, that is. You get some type safety for free this way too.

Upvotes: 0

daniloquio
daniloquio

Reputation: 3902

A variation on @ajalexander answer to make it a single instruction.

string parameter = "name";
int uniqueCount = list.Select(x => parameter == "Id" ? x.Id : x.Name).Distinct().Count();

Upvotes: 0

Bob Vale
Bob Vale

Reputation: 18474

A quick a dirty method would be as follows (assume that field holds the name)

var param=Expression.Parameter(typeof(User),"i");
var property=Expression.Property(param,field);
var select=Expression.Convert(property,typeof(Object));
var result=items.GroupBy ((Func<User,object>)Expression.Lambda(select,param).Compile()).Count();

Result will now contain your answer

Upvotes: 0

Roy Dictus
Roy Dictus

Reputation: 33139

This should do what you want:

int Unique(string parameterName)
{
    List<Whatever> subList = new List<Whatever>();
    if (parameterName == "Id")
    {
        subList = data.Select(x => x.Id);
    } else {
        subList = data.Select(x => x.Name)
    }

    return subList.Distinct().Count();
}

Upvotes: 0

ajalexander
ajalexander

Reputation: 121

If I understand your question correctly (you want to know the count of users having a distinct Id or distinct Name), you could do the following:

int uniqueByIdCount = list.Select(x => x.Id).Distinct().Count();
int uniqueByNameCount = list.Select(x => x.Name).Distinct().Count();

Upvotes: 3

Related Questions