Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

using linq to get unique values

Status
Not open for further replies.

gib99

Programmer
Mar 23, 2012
51
CA
Hello,

I'm a complete newbie to linq.

I'm trying to figure out how to get an array of objects out of another array of objects filtering by distinct fields.

The source array consists of instances of a clsFileRecord class. It has these fields:

bool Exists;
string FolderPath;
string FileName;
string FileSize;

I want to filter the source array by FolderPath. I want to grab the instances of the clsFileRecord for which the FolderPath is unique. In other words, as I iterate through the source array, if I haven't yet encountered a clsFileRecord whose Folder path is "x/y/z", then added to the destination array. If I have already encountered a clsFileRecord whose Folder path is "x/y/z", ignore it.

In the end, each clsFileRecord in the destination array should have a unique FolderPath. I'm not worried about different FileNames as that field is going to be ignored in the destination array.

Can someone please help me work out a linq statement that will accomplish this? Thank you very much.
 
Do you know SQL? You use Group By there to get distinct values.
This might help you

Code:
List<clsFileRecord> distinctFolders = allFiles
  .GroupBy(f => f.FolderPath)
  .Select(p => p.First())
  .ToList();

This is making one thing easier than doing that with SQL: To pick a first full object/array item. In SQL you can't combine * (all fields, full object) with Group By, you have to define aggregations on the fields you don't group by.

As you only need the folder path, you don't need to select full File objects, you might create a list of only file paths. By the way I suggest you rather work with Lists than arrays, both implement IEnumarable, but Lists are more versatile, generic (strongly typed) collections are even better. If you insist on arrays you can of course also use ToArray(), don't forget to declare the variable for the result as array, then.

So as you only want the paths, you can limit yourself to only select that single class field:

Code:
List<String> distinctFolders = allFiles
  .GroupBy(f => f.FolderPath)
  .Select(p => p.First().FolderPath)
  .ToList();

Untested. You might need to fiddle a bit with this, but it should give you an idea.

Bye, Olaf.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top