Home > Back-end >  How to concat item in list with condition
How to concat item in list with condition

Time:03-01

I'm beginner to use linq in C#. I want to concat same items in list using linq when second data of item exist in ref list. I try to select new list by splitting with delimter but I can't get the expected result.

You find as below my code that i used :

using System;
using System.Collections.Generic;   
using System.Linq;

public class Program
{   
    List<String> ref_list = new List<String>();
    List<String> new_list = new List<String>();
    String exist_pattern = "|T";
    
    public bool CheckExistData(String data)
    {
        if (ref_list.Any(item => item == data))
            return true;
        return false;
    }
    
    public void Main()
    {
        ref_list.Add("X2014");
        ref_list.Add("PN14");
        
        new_list.Add("new|P7787");
        new_list.Add("data|987AA");
        new_list.Add("pnal|PN14");
        new_list.Add("mapping|884AW");
        new_list.Add("larou|X2014");
        new_list.Add("data2|PAWLL");
        
        new_list= new_list.Select(r => string.Concat(r, "|T")).Where(s=> CheckExistData(s.Split('|')[1])).ToList();
            
    }
}

Expected Result :

new|P7787
data|987AA
pnal|PN14|T
mapping|884AW
larou|X2014|T
data2|PAWLL

CodePudding user response:

If you want to use linq than you can write it into the Select Part

new_list = new_list.Select(l => CheckExistData(l.Split('|')[1]) ? l exist_pattern : l).ToList();

CodePudding user response:

I think for loop is more suitable than linq in your case. linq is a query language, but you want to update the orignal list.

            for (int i = 0; i < new_list.Count; i  )
            {
                string item = new_list[i];
                string[] parts = item.Split(new char[] { '|' });
                //assert parts.Length == 2
                if (ref_list.Contains(parts[1]))
                {
                    new_list[i] = item   exist_pattern;
                }
            }

Here's code if you really want linq. But I really think first approach is better, more straitforward, and maintainable.

  1. The linq way recreates all items, think if you have millions of items, but only one item matches, the performance is worse.
  2. If you have other logic in the check than just Contains, more than true or false, then it is harder to construct a linq without introducing a third (including anonymous) type or function.
            new_list = new_list
                .Select(x => ref_list.Contains(x.Split(new char[] { '|' })[1])
                ? x   exist_pattern
                : x)
            .ToList();
  • Related