I have the following code:
fo开发者_如何学编程reach (Logs log in _logsDutyStatusChange)
{
string driverid = log.did;
}
How would I only add distinct driver ID's to the driverid string?
Thanks
You should do:
foreach (string id in _logsDutyStatusChange.Select(x=>x.did).Distinct())
{
string driverid = id;
}
mhh ... maybe use IEnumerable< T >
's Distinct()
function?
Your code isn't adding anything right now, it's just setting a string (declared in the scope of the loop) to each value. The end result would be only the last value, and it would be out of scope to the following code anyway. If you're trying to append them all to a string, separated by commas, e.g., try this:
string driverids = string.Join(",", _logsDutyStatusChange
.Select(item=>item.did)
.Distinct()
.ToArray());
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);
}
First, create a comparer 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 that takes an instance of the equality comparer:
foreach(var log in _logsDutyStatusChange.Distinct(new LogComparer()))
{
// Work with each distinct log here
}
Instead of foreach'ing _logsDutyStatusChange, you could use LINQ to get a collection of distinct and loop through those, instead:
foreach (Logs log in _logsDutyStatusChange.Select(l => l.did).Distinct())
{
//Handling code here
}
Implementation will depend exactly on what you intend to do with the results.
You can use Distinct if your Logs class implements IEquatable
Otherwise, a quick 'hacky' fix can 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 have 'automagic' comparing/equating as well
Here's 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()
doesn't quite work here, as it will only get you the distinct did
s.
精彩评论