Click here to Skip to main content
15,896,557 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to validate a duplicate value in the list object using c#. i am parsing xml string with multiple nodes and setting to a list object
I am looping through the list object after assigning the xml node values.
while doing so i need to show validation message if a Ref No is duplicated based on the row count
I am always getting reference no: duplicate message.

What I have tried:

My xml node is as below:
XML
<OriginatorRegistrationRequest>
    <HEADER>
        <Contract_Ref_No>4092</Contract_Ref_No>
        <Source>UTIL</Source>
    </HEADER>
    <BODY>
        <OriginatorDetails>
            <Ref_No>14492</Ref_No>
          </OriginatorDetails>
         <OriginatorDetails>
            <Ref_No>14492</Ref_No>
          </OriginatorDetails>
     </BODY>
</OriginatorRegistrationRequest>


Code tried is as below:
C#
public List<OUT_200_DETAIL> objOUT_200_DETAIL { get; set; }
foreach (OUT_200_DETAIL objOUT_200_DETAIL in objOUT_200_CONTROL.objOUT_200_DETAIL)
{
    if (objOUT_200_CONTROL.objOUT_200_DETAIL[index].RefNo.Contains(objOUT_200_DETAIL.RefNo.Trim()))
    {
        Error += Environment.NewLine + "Row " + Count + "-Reference No: already exists";
    }
}
Posted
Updated 10-Sep-21 3:43am
v5
Comments
CHill60 10-Sep-21 5:50am    
You forgot to put any code in your loop
Richard MacCutchan 10-Sep-21 5:57am    
FOREACH item in XML_NODES
BEGIN
    IF LIST contains item.refno
        PRINT "validation message
    ELSE
        ADD item.refno to LIST
END
PIEBALDconsult 10-Sep-21 9:44am    
Aren't you matching each node to itself? Or always matching against the first?

1 solution

Why not just use Linq methods?
C#
public class MyClass
    {
    public int Id { get; set; }
    public string Name { get; set; }
    public override string ToString()
        {
        return $"ID: {Id}, Name: \"{Name}\"";
        }
    }

C#
List<MyClass> items = new List<MyClass>();
items.Add(new MyClass() { Id = 1, Name = "One" });
items.Add(new MyClass() { Id = 2, Name = "Two" });
items.Add(new MyClass() { Id = 2, Name = "Two Again" });
items.Add(new MyClass() { Id = 1, Name = "One Again" });
items.Add(new MyClass() { Id = 3, Name = "Three" });
var duplicates = items.GroupBy(x => x.Id).SelectMany(g => g.Skip(1));
Console.WriteLine($"Duplicates exist:\n   {string.Join("\n   ", duplicates)}");
Run that, and you get a list of duplicates:
Duplicates exist:
   ID: 1, Name: "One Again"
   ID: 2, Name: "Two Again"
 
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