0

I have a two lists: FPTStaticDataManagedStrategyAssetlist & FPTDocManagedStrategyList.

I want to be able to choose a random asset from FPTStaticDataManagedStrategyAssetlist, that doesn't already exist in FPTDocManagedStrategyList to stop duplicates.

This is my code currently

FPTStaticDataManagedStrategyAssetlist[random.Next(0, FPTStaticDataManagedStrategyAssetlist.Count())];

but obviously it can include duplicated items. Any Ideas?

Marc Howard
  • 395
  • 2
  • 6
  • 25
  • Can you guarantee that there will always be some items in FPTStaticDataManagedStrategyAssetlist that are not in FPTDocManagedStrategyList? What do you expect is the relative proportion of items that are not in the second list? The answers to these questions will determine the best approach. – Matthew Watson Jan 29 '14 at 09:58

2 Answers2

2

You can use the Except method:

var temp = FPTStaticDataManagedStrategyAssetlist.Except(FPTDocManagedStrategyList).ToList();
if (temp.Count > 0)
{
    var item = temp[random.Next(0, temp.Count)];
}
else
{
    // no items to choose from...
}

You can also avoid materializing the result of Except to a list, by using the method posted by Jon Skeet here.

Community
  • 1
  • 1
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
1
//Filter away duplicates
var listTemp = listA.Where(i=> !listB.Contains(i)).ToList();
//Select random
var randomItem = listTemp[random.Next(0, listTemp.Count())];
Robert Fricke
  • 3,637
  • 21
  • 34