Click here to Skip to main content
15,072,209 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:

Code tried is as below:
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";
Updated 10-Sep-21 3:43am
CHill60 10-Sep-21 5:50am
You forgot to put any code in your loop
Richard MacCutchan 10-Sep-21 5:57am
    IF LIST contains item.refno
        PRINT "validation message
        ADD item.refno to LIST
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?
public class MyClass
    public int Id { get; set; }
    public string Name { get; set; }
    public override string ToString()
        return $"ID: {Id}, Name: \"{Name}\"";

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"

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