0

Good day all.

Let's say for example I have a custom type:

public struct Group {
    public string GroupName;
    public int someInt;
}

And say I have an array of this type:

public Group[] Groups;

I want to check to see if Groups has two or more Group items with the same GroupName. In pseudo-code it would look like:

if (Groups has two or more Group items with the same name) {
    // we have a problem
}

Will be glad if someone helps. Thanks in advance!

Tayab
  • 311
  • 2
  • 13
  • 2
    You should check the `IComparable` interface: https://msdn.microsoft.com/en-us/library/system.icomparable%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 **or** https://msdn.microsoft.com/en-us/library/4d7sx9hd(v=vs.110).aspx – Jeroen van Langen Mar 21 '16 at 21:01

3 Answers3

3

You could do this:

if(Groups.GroupBy(e=>e.GroupName).Count()>1)
{
 //...
}
ocuenca
  • 38,548
  • 11
  • 89
  • 102
  • I really thought this would work but no matter how many Group items in Groups with the same GroupName it always equates to 1. Please check your code and get back to me :( – Tayab Mar 21 '16 at 21:17
  • Could you add to your question a collection of data you are using to test? – ocuenca Mar 21 '16 at 21:19
  • 1
    @Tayab, believe me or not, but this piece of code should works as well! – Maciej Los Mar 21 '16 at 21:21
  • @Tayab, now that I see the answer that you marked as the correct one, I realize what you really needed to know is if there were some repeated groups, I thought you want to check if your list of groups belong to a same group – ocuenca Mar 21 '16 at 21:28
  • @octavioccl No worries, it's probably my fault I didn't explain better. Thanks for the quick answer anyway, you're a good person :) – Tayab Mar 21 '16 at 21:35
1
if(Groups.GroupBy(e=>e.GroupName).Count() < Groups.Count)
{
    // we have a problem
}
serdar
  • 1,564
  • 1
  • 20
  • 30
0

I think there might be a better solution but, you can try this.

var results = (from p in Groups
              group p by p.GroupName into g
              select new { GroupName = g.Key, Total = g.Count 
              }).Where(c=>c.Total>1).ToList();

If(results.Count()>1)
{

}
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
COLD TOLD
  • 13,513
  • 3
  • 35
  • 52