Click here to Skip to main content
15,850,359 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to compare the same "PhoneNumber" attributes having the same "ID" for each element

XML
<List>
      <Connect ID="ID1" PhoneNumber="453585644878">
 
      </Connect>
      <Connect ID="ID1" PhoneNumber="453585644878">
 
      </Connect>
      <Connect ID="ID2" PhoneNumber="45655556658">
       </Connect>
      <Connect ID="ID2" PhoneNumber="96685688787">
      </Connect>
      <Connect ID="ID3" PhoneNumber="5766855577">
      </Connect>
      <Connect ID="ID3" PhoneNumber="8565657787">
      </Connect>
      <Connect ID="ID3" PhoneNumber="4565775235">
      </Connect>
      <Connect ID="ID4" PhoneNumber="44545454545">
      </Connect>
 </List>

for example in , the first two connect equivalent phone numbers and in the other non-equivalent numbers.

What I have tried:

C#
var xElementConnectiveList = xdoc.Descendants("List").Descendants("Connect ").ToList();


           var groupconnective = from xElementConnective in xElementConnectiveList
                                       group xElementConnective.Attribute("ID").Value by xElementConnective.Attribute("ID").Value into xElementConnectiveGroup
                                       orderby xElementConnectiveGroup.Key
                                       select xElementConnectiveGroup.Key;
Posted
Updated 23-Aug-22 4:19am
v2

1 solution

Seems simple enough:
C#
var connectElements = xdoc.Descendants("List").Descendants("Connect");

var groupedElements = from el in connectElements
                      group el by el.Attribute("ID").Value into g
                      select g;

foreach (IGrouping<string, XElement> group in groupedElements)
{
    var telephoneNumbers = new HashSet<string>(group.Select(el => el.Attribute("PhoneNumber").Value), StringComparer.Ordinal);
    if (telephoneNumbers.Count == 1)
    {
        Console.WriteLine("{0}: All numbers match.", group.Key);
    }
    else
    {
        Console.WriteLine("{0}: Found {1} different numbers.", group.Key, telephoneNumbers.Count);
    }
}
Output:
ID1: All numbers match.
ID2: Found 2 different numbers.
ID3: Found 3 different numbers.
ID4: All numbers match.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900