开发者

LINQ Basics, How do I do a groupby and get a string at the end?

Hello I have a class like so

class myclass
{
    public string string1;
    public string string2;
    public string string3;
}

And I have a list of them and I want to produce a list of strin开发者_开发知识库gs of unique string1 s.

List<myclass> myInstance = GetInstanceOfMyClass();

MethodThatRequiresListOfStrings( myInstance.GroupBy(p => ??????? .ToList<string>());

What would replace the ??????? ?

I can't believe I've gone this long without doing a group by with a lambda expression...


In this case, I would not use a grouping at all. If you just want distinct string1 values, use Distinct().

myInstance.Select(obj => obj.string1).Distinct(); // .ToList()

If you want to learn how to group, consider this

myInstance.GroupBy(obj => obj.string1).Select(grp => grp.Key); // .ToList()

However, again, I would go with the first option.


I want to produce a list of strings of unique string1 s.

In that case, you don't need a grouping operation; you probably want to use the Distinct operator:

var distinctString1s = myInstance.Select(p => p.string1)
                                 .Distinct()
                                 .ToList();

MethodThatRequiresListOfStrings(distinctString1s);

In other words, construct a new sequence by projecting each myclass instance to its string1 field, and then load the distict items of that sequence into a list.


No GroupBy needed:

var distinctString1s = myInstance.Select(x => x.string1)
                                 .Distinct()
                                 .ToList();


MethodThatRequiresListOfStrings(myInstance.Select(s=>s.string1).Distinct().ToList());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜