C # foreach get only individual values

I have the following code:

foreach (Logs log in _logsDutyStatusChange) { string driverid = log.did; } 

How do I add only a single driver identifier to the driver string?

thanks

+7
source share
8 answers

Your code is not adding anything right now, it just sets a line (declared in the loop area) for each value. The final result will only be the last value, and in any case, it will be out of sight for the following code. If you are trying to add all of them to a comma separated string, for example, try the following:

 string driverids = string.Join(",", _logsDutyStatusChange .Select(item=>item.did) .Distinct() .ToArray()); 
+4
source

You should:

 foreach (string id in _logsDutyStatusChange.Select(x=>x.did).Distinct()) { string driverid = id; } 
+10
source

mhh ... is it possible to use the IEnumerable< T > Distinct() function?

+6
source

First create a comparison class and implement the IEqualityComparer<Log> interface:

 public class LogComparer : IEqualityComparer<Log> { public bool Equals(Log one, Log two) { return one.did.Equals(two.did); } public int GetHashCode(Log log) { return log.did.GetHashCode(); } } 

And then use the overload of the Enumerable.Distinct() method, which accepts an equality mapping instance:

 foreach(var log in _logsDutyStatusChange.Distinct(new LogComparer())) { // Work with each distinct log here } 
+1
source

Instead of foreach'ing _logsDutyStatusChange, you can use LINQ to get a collection of individual elements and loop through them:

 foreach (Logs log in _logsDutyStatusChange.Select(l => l.did).Distinct()) { //Handling code here } 

The implementation will depend on what you intend to do with the results.

+1
source

This should work (without linq):

 Hashset<string> alreadyEncountered = new Hashset<string>(); foreach (Logs log in _logsDutyStatusChange) { if(alreadyEncountered.Contains(log.did)) { continue; } string driverid = log.did; alreadyEncountered.Add(driverid); } 
+1
source

You can use Distinct if the Logs class implements IEquatable

Otherwise, a quick “hacked” fix might be to use something like

 foreach (var group in _logsDutyStatusChange.GroupBy(l => new { log.did, .... more identifying fields }) { string driverid = group.Key.did; } 

C # 4.0 tuples also have "automatic" comparison / equalization

0
source

Here is one approach:

 HashSet<string> SeenIDs = new HashSet<string>(); foreach (Logs log in _logsDutyStatusChange) { if (SeenIDs.Contains(log.did)) break; SeenIDs.Add(log.did); string driverid = log.did; } 

Distinct() does not work here, since it will only highlight did s.

0
source

All Articles