简体   繁体   中英

Display a single message with records when Id exists in C# Linq

I have to check record if exists then display a message with Id stating that following Id's exists. As I have written the message in a loop so the message is repeated. If I write the console message outside the loop then scope ends.

Current output :

Cannot delete as Id 1 exists.
Cannot delete as Id 2 exists.

Required Output :

Cannot delete as Id 1,2 exists.

public class Program
{

    public int Id { get; set; }

    static void Main(string[] args)
    {
        List<Program> client = new List<Program>();

        client.Add(new Program { Id = 1 });
        client.Add(new Program { Id = 2 });
        client.Add(new Program { Id = 3 });
        client.Add(new Program { Id = 4 });
        client.Add(new Program { Id = 5 });


        List<Program> server = new List<Program>();
        server.Add(new Program { Id = 2});
        server.Add(new Program { Id = 4 });

        foreach (var c in client)
        {
            var r = server.Any(x => x.Id == c.Id);
            if (r==true)
            {
                Console.WriteLine(String.Format("Cannot delete as {0} exists",c.Id));    
            }

        }

        Console.ReadLine();
    }
}

Use this

public class Program
{

    public int Id { get; set; }

    static void Main(string[] args)
    {
        List<Program> client = new List<Program>();

        client.Add(new Program { Id = 1 });
        client.Add(new Program { Id = 2 });
        client.Add(new Program { Id = 3 });
        client.Add(new Program { Id = 4 });
        client.Add(new Program { Id = 5 });


        List<Program> server = new List<Program>();
        server.Add(new Program { Id = 2});
        server.Add(new Program { Id = 4 });
        List<int> lst = new List<int>();
        foreach (var c in client)
        {
            var r = server.Any(x => x.Id == c.Id);
            if (r==true)
            {
                lst.Add(c.Id);

            }

        }

        if(lst.Count() > 0)
            Console.WriteLine(String.Format("Cannot delete as {0} exists",string.Join(",",lst)));    

        Console.ReadLine();
    }
}

This might not be perfect, but will work for you, so modify your code to

string allID = "";   
foreach (var c in client)
{
    var r = server.Any(x => x.Id == c.Id);

    if (r==true)
    {
        allID += c.Id + ","; //will append values of matched c.ID with a comma
    }
}

allID = allID.Remove(allID.Length - 1); //Removes the last extra comma
Console.WriteLine(String.Format("Cannot delete as {0} exists", allID)); 

Output:

Cannot delete as Id 1,2 exists.

You should initialize the string outside the loop and build it when you find new conflicting Ids. Also, check that there is at least 1 conflicting Id in the string before outputing an error message.

string existingIds = "";

foreach (var c in client)
{
    var r = server.Any(x => x.Id == c.Id);
    if (r == true)
    {
        if (existingIds.Equals(string.Empty))
            existingIds += c.Id;
        else
            existingIds += "," + c.Id;
    }
}

if (existingIds.Equals(string.Empty))
    Console.WriteLine(String.Format("Cannot delete as {0} exists", existingIds)); 

There are many ways to get the Intersect of two collections:

var intersect = client.Select(c => c.Id).Intersect(server.Select(s => s.Id));    // 2, 4

if (intersect.Any())
    Console.WriteLine($"Cannot delete as Id {string.Join(", ", intersect)} exists");

or a bit more efficient:

var server = new HashSet<int> { 2, 4 };
server.IntersectWith(client.Select(c => c.Id));

if (server.Count > 0)
    Console.WriteLine($"Cannot delete as Id {string.Join(", ", server)} exists");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM