tags:

views:

58

answers:

3

Say I have a class:

public class theclass
{
  public string a;
  public string b;
  public string c;
}

Yes. It's a bad class. Moving on. Say I have a 100 value array of this class. Is there a quick way with linq to get a list of strings with all of the values of b for the contents of the array?

+2  A: 
var valuesForB = yourArray.Select((arrayMember) => arrayMember.b);
Jimmy Hoffa
+3  A: 

Yes.

IEnumerable<string> bValues = myArray.Select(myClass => myClass.b);
nukefusion
I know it's pedantic, but he did ask for a `List<string>`...
fearofawhackplanet
You're right, it is pedantic.
nukefusion
well if he doesn't know `Select`, he probably doesn't know `ToList` either, so it's worth including in the example.
fearofawhackplanet
@fearofawhackplanet: agreed.
nukefusion
Just started fiddling with linq, so I'm still working through things.
quillbreaker
+5  A: 
TheClass[] myClasses = GetTheArray();

List<string> = myClasses.Select(c => c.A).ToList();

(I changed your class/property names to PascalCase, as per coding standard convention)

fearofawhackplanet
hmmm, that's not the coding standard we use. Different shops use different coding standards. We don't all drink the MS kool-aid.
Muad'Dib
@Muad'Dib: even though it goes against the entire BCL? I'll happily drink the "kool-aid" in this case.
Kent Boogaart
@fearofawhackplanet - I know it's pedantic, but he did ask for the values of b, rather than a ;) - sorry, couldn't resist :)
Alex Humphrey
lol true :) ...
fearofawhackplanet
I'm not going to follow some standard just bc MS says I should.
Muad'Dib
@Maud'Dib - correct, you shouldn't just because Microsoft says so. But people generally find code that uses consistent naming conventions easier to read. Because I use loads of BCL calls, my code follows the same conventions. What reasons do you have to not follow those conventions?
Alex Humphrey
@Muad'Dib: it sounds more like you're not following the convention simply because it originates from Microsoft.
Kent Boogaart
Bc my boss gave me a list of conventions which he asked me to follow, which may or may not match the MS convention. Just bc MS (or anyone else) says so, doesn't make it so.
Muad'Dib