English 中文(简体)
如何在使用倾角q的类型清单中取代某些具体的措辞?
原标题:How to replace some particular string in a list of type string using linq?
  • 时间:2011-11-09 09:45:15
  •  标签:
  • c#
  • linq

然而,我都有一些项目的类型清单。 i 想用林克替换一些物品,如何做到这一点? 我的以下法典是罚款的,但想利用林克的力量在单一法典行中这样做。

我的法典如下:

List<string> listcolumns = columns.ToList();//Array to list

if (listcolumns.Contains("HowToReplace") && listcolumns.Contains("HowTo Replace"))
{
    int index = 0;
    index = listcolumns.IndexOf("HowToReplace");
    if (index > 0)
    {
        listcolumns.RemoveAt(index);
        listcolumns.Insert(index, "HowTo Replace");
    }
    index = listcolumns.IndexOf("HowToReplace");
    if (index > 0)
    {
        listcolumns.RemoveAt(index);
        listcolumns.Insert(index, "HowTo Replace");
    }
    columns = listcolumns.ToArray<string>();//List to array
}
最佳回答

With Linq:

listColumns.Select<string,string>(s => s == "HowToReplace" ? "HowTo Replace" : s).ToArray();

如无林克:

 for (int i=0; i<listColumns.Length; i++) 
    if (ListColumns[i] == "HowToreplace") ListColumns[i] ="HowTo Replace");
问题回答
static class LinqExtensions
{
    public static IEnumerable<T> Replace<T>(this IEnumerable<T> items, Predicate<T> condition, Func<T, T> replaceAction)
    {
        return items.Select(item => condition(item) ? replaceAction(item) : item);
    }
}

然后,你可以这样使用。

var names = new[] { "Hasan", "Jack", "Josh" };
names = names.Replace(x => x == "Hasan", _ => "Khan").ToArray();
List<String> lstString = new List<string> { "find", "find1","find", "find2" };

//all  find  will be replaced with  replace 
lstString.Select(str=>str.Replace("find","replace"));




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签