I have List consists of {"a","b","c"} i have string s contains{"alphabets"} .i like to add the list to string. i need final output in s like this `{"alphabetsabc"}. i like to do this using linq.
Using LINQ, or even Join, would be overkill in this case. Concat will do the trick nicely:
string s = "alphabets";
var list = new List<string> { "a", "b", "c" };
string result = s + string.Concat(list);
(Note that if you're not using .NET4 then you'll need to use string.Concat(list.ToArray()) instead. The overload of Concat that takes an IEnumerable<T> doesn't exist in earlier versions.)
Why not just string.Join? Using Linq would be an overkill.
Quick & dirty:
List<string> list = new List<string>() {"a", "b", "c"};
string s = "alphabets";
string output = s + string.Join("", list.ToArray());
You need the Aggregate method, if you really want to use LINQ.
Related
I want to convert an ArrayList to a List<string> using LINQ. I tried ToList() but that approach is not working:
ArrayList resultsObjects = new ArrayList();
List<string> results = resultsObjects.ToList<string>();
Your code actually shows a List<ArrayList> rather than a single ArrayList. If you're really got just one ArrayList, you'd probably want:
ArrayList resultObjects = ...;
List<string> results = resultObjects.Cast<string>()
.ToList();
The Cast call is required because ArrayList is weakly typed - it only implements IEnumerable, not IEnumerable<T>. Almost all the LINQ operators in LINQ to Objects are based on IEnumerable<T>.
That's assuming the values within the ArrayList really are strings. If they're not, you'll need to give us more information about how you want each item to be converted to a string.
I assume your first line was meant to be ArrayList resultsObjects = new ArrayList();.
If the objects inside the ArrayList are of a specific type, you can use the Cast<Type> extension method:
List<string> results = resultsObjects.Cast<string>().ToList();
If there are arbitrary objects in ArrayList which you want to convert to strings, you can use this:
List<string> results = resultsObjects.Cast<object>().Select(x => x.ToString())
.ToList();
You can also use LINQ's OfType<> method, depending on whether you want to raise an exception if one of the items in your arrayList is not castable to the desired type. If your arrayList has objects in it that aren't strings, OfType() will ignore them.
var oldSchoolArrayList = new ArrayList() { "Me", "You", 1.37m };
var strings = oldSchoolArrayList.OfType<string>().ToList();
foreach (var s in strings)
Console.WriteLine(s);
Output:
Me
You
You can convert ArrayList elements to object[] array using ArrayList.ToArray() method.
List<ArrayList> resultsObjects = new List<ArrayList>();
resultsObjects.Add(new ArrayList() { 10, "BB", 20 });
resultsObjects.Add(new ArrayList() { "PP", "QQ" });
var list = (from arList in resultsObjects
from sr in arList.ToArray()
where sr is string
select sr.ToString()).ToList();
This is something I have always wondered about, and looked up a few times but have never figured out.
So basically what I want to do is get something to this effect:
List<string> strings = new List<string>(){"a","b","c"};
string aString = foreach(string s in strings){ if (s == "c") return s;}
so then after that, aString has the value "c".
I have tried using lambda expressions, maybe I just cant get them to work right, or maybe there is just no way to do this.
And obviously I want to do something a bit more complicated than in my example above, but it will work the same way.
Possible? not possible?
You should use the FirstOrDefault Extension method.
List<string> strings = new List<string>(){"a","b","c"};
return strings.FirstOrDefault(s=>String.Equals(s, "a"));
You can use LINQ (to objects):
List<string> strings = new List<string>(){"a","b","c"};
string aString = strings.Where(x => x.Equals("a")).FirstOrDefault();
The Where() methods iterates through the enumerable, and "returns" each element that satisfies the lambda. To get the first such element, you can chain on the FirstOrDefault() method (which will return default(string) if no elements meet the criteria.)
As #MichaelGraczyk points out, you can actually reduce the call to only FirstOrDefault(), since it has an overload that accepts a predicate:
string aString = strings.FirstOrDefault(x => x.Equals("a"));
There are a number of other useful methods available, which you can read about here.
It's kind of pointless in this particular example because you already know the string you want but in any case I think this is what you're trying to do...
List<string> strings = new List<string>(){"a","b","c"};
string aString = strings.Find((string s) => s == "a");
Say that for debugging purposes, I want to quickly get the contents of an IEnumerable into one-line string with each string item comma-separated. I can do it in a helper method with a foreach loop, but that's neither fun nor brief. Can Linq be used? Some other short-ish way?
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
public static void Main()
{
var a = new []{
"First", "Second", "Third"
};
System.Console.Write(string.Join(",", a));
}
}
string output = String.Join(",", yourEnumerable);
String.Join Method (String, IEnumerable
Concatenates the members of a constructed IEnumerable collection of
type String, using the specified separator between each member.
collection.Aggregate("", (str, obj) => str + obj.ToString() + ",");
(a) Set up the IEnumerable:
// In this case we are using a list. You can also use an array etc..
List<string> items = new List<string>() { "WA01", "WA02", "WA03", "WA04", "WA01" };
(b) Join the IEnumerable Together into a string:
// Now let us join them all together:
string commaSeparatedString = String.Join(", ", items);
// This is the expected result: "WA01, WA02, WA03, WA04, WA01"
(c) For Debugging Purposes:
Console.WriteLine(commaSeparatedString);
Console.ReadLine();
IEnumerable<string> foo =
var result = string.Join( ",", foo );
to join large array of strings to a string, do not directly use +, use StringBuilder to iterate one by one, or String.Join in one shot.
C# Array, How to make data in an array distinct from each other?
For example
string[] a = {"a","b","a","c","b","b","c","a"};
how to get
string[]b = {"a","b","c"}
Easiest way is the LINQ Distinct() command :
var b = a.Distinct().ToArray();
You might want to consider using a Set instead of an array. Sets can't contain duplicates so adding the second "a" would have no effect. That way your collection of characters will always contain no duplicates and you won't have to do any post processing on it.
var list = new HashSet<string> { };
list.Add("a");
list.Add("a");
var countItems = list.Count(); //in this case countItems=1
An array, which you start with, is IEnumerable<T>. IEnumerable<T> has a Distinct() method which can be used to manipulate the list into its distinct values
var distinctList = list.Distinct();
Finally,IEnumerable<T> has a ToArray() method:
var b = distinctList.ToArray();
I think using c# Dictionary is the better way and I can sort by value using LINQ
Here's what I'm trying to do:
ObjectA
{
int ID;
string name;
}
I want to convert Dictionary to List where the strings in the list are the .name values of the ObjectAs in the dictionary. Obviously I could manually iterate over the dictionary values and build the list that way, but I was hoping there'd be a simpler or faster way in C# / .NET. A LINQ solution is fine, if it's simpler and faster than/as fast as:
List<string> aNames = new List<string>();
foreach(ObjectA a in DictionaryA.Values)
aNames.Add(a.name);
Here's the non-query-expression form of Matthew's answer:
var names = DictionaryA.Values.Select(x => x.name).ToList();
(I tend not to use query expressions when I'm just doing a single select or a single where, especially if I also need to call another method such as ToList.)
Alternatively:
var names = DictionaryA.Select(x => x.Value.name).ToList();
(from val in DictionaryA.Values select val.name).ToList()
There's plenty of ways to do this once you have a query:
IQueryable<string> query = DictionaryA.Values.Select(v => v.name);
//use the Constructor of List<T> that accepts IEnumerable<T>
List<string> aNames = new List<string>(query);
//
//or use the AddRange method for existing Lists
List<string> aNames = new List<string<();
aNames.AddRange(query);
//
//or use the Enumerable.ToList extension method
List<string> aNames = query.ToList();