Using LINQ To Interleave Two Lists - c#

So here is what I'm attempting to do:
symbolList: 1,1,1,2,2,2
valueList: a1,b1,c1,a2,b2,c2
result: 1|a1|b1|c1,2|a2|b2|c2
The a,b,c for each symbol are all different values
For each symbol there will be the same amount of corresponding values. So for symbol 1, there are three values that I would like joined with it. For symbol 2 I want the second set of three values joined to it, etc.
However, with my current implementation, I currently get:
result: 1|a1|b1|c1|a2|b2|c2, 2|a1|b1|c1|a2|b2|c2
Here's my current code:
List<string> results = symbolList.Distinct().Select(f =>
String.Join("|", new List<string>() { f }.Concat(valueList))).ToList();
string value = string.Join(",", results);
I've attempted to use group by in some fashion, but haven't found a viable result doing that. Any help is greatly appreciated.

From your description it looks like the paired index matters, you are not trying to do a blind interleave. Here is how to do it with a GroupBy, I also put a 3 in the middle to demonstrate the ordering.
List<string> symbolList = new List<string>() { "1", "1", "3", "2", "2", "2" };
List<string> valueList = new List<string>() { "a1", "b1", "c3", "a2", "b2", "c2" };
var items = symbolList.Zip(valueList, (symbol, value) => new {symbol, value}) //pairs the like indexes with each other in to an anonymous type.
.GroupBy(pair => pair.symbol, pair => pair.value) //Group together the values that share the same symbol
.OrderBy(group => group.Key) //optional, only if you want the output to be 1,2,3
.Select(group => String.Join("|", (new[] {group.Key}).Concat(group))); //Build up the "|" separated groups.
var result = String.Join(",", items); //Join together the groupings separated by ","
Console.WriteLine("result: " + result);
Click to Run
It gives the result result: 1|a1|b1,2|a2|b2|c2,3|c3

Can you please try this out:
List<string> symbolList = new List<string>() { "1", "1", "1", "2", "2", "2" };
List<string> valueList = new List<string>() { "a", "b", "c", "a", "b", "c" };
string value = string.Join(",", symbolList.Distinct().
Select(f => String.Join("|", new List<string>() { f }
.Concat(valueList.Distinct()))).ToList());
Console.WriteLine("result: " + value);
This code gives me result: "1|a|b|c,2|a|b|c".
I hope this is what you want.

While not the answer to the original question, to strictly answer the title (which is what I came here looking for, just simply interleaving two lists):
var interleaved = list1.Zip(list2, (a, b) => new[] { a, b }).SelectMany(p => p);
Example:
var l1 = Enumerable.Range(0, 10).Select(i => (char) ('0' + i));
var l2 = Enumerable.Range(0, 10).Select(i => (char) ('A' + i));
var interleaved = l1.Zip(l2, (a, b) => new[] { a, b }).SelectMany(p => p);

Related

Tuple to have contains and not contains list C#

I have a query like this:
var foundData = await DatabaseContext.Set<TableA>()
.AsNoTracking()
.Where(x => list.Contains(x.Code))
.Select(x => x.Code)
.ToListAsync()
.ConfigureAwait(false);
var notFoundData = await DatabaseContext.Set<TableA>()
.AsNoTracking()
.Where(x => !list.Contains(x.Code))
.Select(x => x.Code)
.ToListAsync()
.ConfigureAwait(false);
As this query hits the database twice and also, I don't want to retrieve all the records from the database and then filter. Is it possible to have a List<tuple> which does it in one query like
Suppose the database contains:
A,B,C,D,E
In reality, database contains millions of records. So does the list.
and list contains A,B,F
So found list will contain: A, B
And notFound will contain: F
So expected output is var (found, notfound) = ?
Does this help you?
var source = new List<string> { "A", "B", "C", "D", "E" };
var target = new List<string> { "A", "B", "F" };
var foundOrNot = target.Select(s => new { Value = s, Found = source.Contains(s) });
foreach(var entry in foundOrNot)
{
Console.WriteLine("Value: " + entry.Value + "; Found: " + entry.Found.ToString());
}
https://dotnetfiddle.net/KL9yfK
You can do something as follow:
List<string> records = new List<string> {"A", "B", "C", "D", "E"};
List<string> list = new List<string> {"A", "B", "F"};
var result = records
.GroupBy(r => list.Contains(r))
.ToDictionary(r => r.Key);
var (found, notfound) = (result.ContainsKey(true) ? result[true].Select(g => g) : new List<string>(),
result.ContainsKey(false) ? result[false].Select(g => g) : new List<string>());

How to check if there are multiple of the same values in an array

Say I have an array which has the following values
A B A A B C
How do I run a code which will increment the integer variables a, b, and c according to the amount of the times they occur in the array
You can use GroupBy:
var array = new string[] {"A", "B", "A", "A", "B", "C" };
var counts = array
.GroupBy(letter => letter)
.Select(g => new { Letter = g.Key, Count = g.Count() });
If you want to get the counts individually, you can put everything into a dictionary
var countsDictionary = array
.GroupBy(letter => letter)
.ToDictionary(g => g.Key, g => g.Count());
var aCount = countsDictionary["A"];
var bCount = countsDictionary["B"];
//etc...
Look at the example at the bottom of https://msdn.microsoft.com/en-us/library/vstudio/bb535181%28v=vs.100%29.aspx
It basically does what you need.
var array = new string[] {"A", "B", "A", "A", "B", "C" };
int a = array.Count(p => p == "A");

Linq: Sum() non-integer values

This is a continuation from my previos question:
Linq (GroupBy and Sum) over List<List<string>>
I have a query like so:
var content = new List<List<string>>
{
new List<string>{ "book", "code", "columnToSum" },
new List<string>{ "abc", "1", "10" },
new List<string>{ "abc", "1", "5" },
new List<string>{ "cde", "1", "6" },
};
var headers = content.First();
var result = content.Skip(1)
.GroupBy(s => new { Code = s[headers.IndexOf("code")], Book = s[headers.IndexOf("book")]})
.Select(g => new
{
Book = g.Key.Book,
Code = g.Key.Code,
Total = g.Select(s => int.Parse(s[headers.IndexOf("columnToSum")])).Sum()
});
This works fine but I'm just wondering how I can handle the case there the columnToSum is empty? So for example this gives me the error "Input string was not in a correct format" as the int.Parse fails
var content = new List<List<string>>
{
new List<string>{ "book", "code", "columnToSum" },
new List<string>{ "abc", "1", "10" },
new List<string>{ "abc", "1", "" },
new List<string>{ "cde", "1", "6" },
};
How can I handle this scenario gracefully?
Why don't you just add a zero onto the front of the string?
s => int.Parse("0" + s[headers.IndexOf("columnToSum")])
Of course, it's a big hack. But it will solve your problem quickly and (quite) readably if the only exceptional case you're really worried about is the empty string.
I wonder where you're getting these empty strings from. If it's something you have control over like a SQL query, why don't you just change your query to give "0" for no value? (As long as the empty column isn't used in a different sense somewhere else in your code.)
One option, use string.All(Char.IsDigit) as pre-check:
Total = g.Select(s => !string.IsNullOrEmpty(s[headers.IndexOf("columnToSum")]) &&
s[headers.IndexOf("columnToSum")].All(Char.IsDigit) ?
int.Parse(s[headers.IndexOf("columnToSum")]) : 0).Sum())
another would be to use int.TryParse:
int val = 0;
// ...
Total = g.Select(s => int.TryParse(s[headers.IndexOf("columnToSum")], out val) ?
int.Parse(s[headers.IndexOf("columnToSum")]) : 0).Sum())
That code assumes that empty string is 0:
Total = g.Where(s => !String.IsNullOrEmpty(s)).Select(s => int.Parse(s[headers.IndexOf("columnToSum")])).Sum()
Unfortunately, this isn't going to look very nice...
g.Select(s => !s[headers.IndexOf("columnToSum")].Any(Char.IsDigit) ?
0 : Int32.Parse(s[headers.IndexOf("columnToSum")])).Sum()
However, you could wrap this up in a nice extension method
public static class StrExt
{
public static int IntOrDefault(this string str, int defaultValue = 0)
{
return String.IsNullOrEmpty(str) || !str.Any(Char.IsDigit) ? defaultValue : Int32.Parse(str);
}
}
...
g.Select(s => s[headers.IndexOf("columnToSum")].IntOrDefault()).Sum();
The extension method give you the flexibility to set whatever default value you want if the str is not a number - it defaults to 0 if the parameter is ommitted.
Using lists here is problematic, and I would parse this into a proper data structure (like a Book class), which I think will clean up the code a bit. If you're parsing CSV files, take a look at FileHelpers, it's great library for these types of tasks, and it can parse into a data structure for you.
That being said, if you'd still like to continue using this paradigm, I think you can get the code fairly clean by creating two custom methods: one for dealing with the headers (one of the few places I'd use dynamic types to get rid of ugly strings in your code) and one for parsing the ints. You then get something like this:
var headers = GetHeaders(content.First());
var result = from entry in content.Skip(1)
group entry by new {Code = entry[headers.code], Book = entry[headers.book] } into grp
select new {
Book = grp.Key.Book,
Code = grp.Key.Code,
Total = grp.Sum(x => ParseInt(x[headers.columnToSum]))
};
public dynamic GetHeaders(List<string> headersList){
IDictionary<string, object> headers = new ExpandoObject();
for (int i = 0; i < headersList.Count; i++)
headers[headersList[i]] = i;
return headers;
}
public int ParseInt(string s){
int i;
if (int.TryParse(s, out i))
return i;
return 0;
}
You can use multiple lines in a lambda expression and return a value at end.
So, instead of
Total = g.Select(s => int.Parse(s[headers.IndexOf("columnToSum")])).Sum()
I would write
Total = g.Select(s => {
int tempInt = 0;
int.TryParse(s[headers.IndexOf("columnToSum")], out tempInt);
return tempInt;
}).Sum()
t = new List<List<string>>
{
new List<string>{ "book", "code", "columnToSum" },
new List<string>{ "abc", "1", "10" },
new List<string>{ "abc", "1", "5" },
new List<string>{ "cde", "1", "6" },
};
var headers = content.First();
var result = content.Skip(1)
.GroupBy(s => new { Code = s[headers.IndexOf("code")], Book = s[headers.IndexOf("book")]})
.Select(g => new
{
Book = g.Key.Book,
Code = g.Key.Code,
Total = g.Select(s => int.Parse(s[headers.IndexOf("columnToSum")]!=""?s[headers.IndexOf("columnToSum")]:0)).Sum()
});

How to use LINQ select something contain string[]

How to use linq to select something fit the conditions below,
I want select the words JUST contains the string in ArStr[], i.e. a,b,c
In the Wordslist, "aabb" don't contain "c", "aacc" don't contain "b", "aabbccd" contain "d".
So they are not the words I want.
Please help.
Wordslist :
aabb
aacc
aaabbcc
aabbbcc
aabbccd
ArStr[] :
"a"
"b"
"c"
Expected Query:
aaabbcc
aabbbcc
IEnumerable<Word> Query =
from Word in Wordslist
where
Word.Value.Contains(ArStr[0]) // 1
&& Word.Value.Contains(ArStr[1]) // 2
&& Word.Value.Contains(ArStr[2]) // 3
select Word;
You can construct a set of white-list characters and then filter those words that are set-equal with that white-list (ignoring duplicates and order).
var chars = new HashSet<char>(ArStr); // Construct white-list set
var query = from word in wordsList
where chars.SetEquals(word) // Word must be set-equal with white-list
select word;
or
var query = wordsList.Where(chars.SetEquals);
As you've probably noticed, the query you've written does return "aabbccd", because that string contain "a", it contains "b", and it contains "c".
Assuming that ArStr can only contain one-character strings, and you want to return strings that contain only the specified characters, so you should say (adapted from Ani's answer):
var chars = new HashSet<char>(ArStr.Select(s => s[0]));
var query = wordslist.Where(w => chars.SetEquals(w.Value));
However, if the ArStr elements could be more than one character long, the problem needs to be better defined, and the solution will be more complicated.
Use this method to evaluate a word if it passes your condition or not:
bool HasValidCharacters(string word)
{
var allowedCharacters = new List<string> { "a", "b", "c" };
return string.Join("", word.GroupBy(c => c)
.Select(g => g.Key)
.OrderBy(g => g))
.Equals(string.Join("", allowedCharacters.OrderBy(c => c)));
}
Then simply call the method to get the required list:
var words = new List<string> { "aabb", "aacc", "aaabbcc", "aabbbcc", "aabbccd" };
var matchingWords = words.Where(HasValidCharacters);
You could try this:
List<String> words = new List<string> { "aabb", "aacc", "aaabbcc", "aabbbcc", "aabbccd" };
List<string> allowed = new List<string> { "a", "b", "c" };
var lst = words.Where(word => allowed.All(a => word.Contains(a) && !Regex.IsMatch(word, "[^" + string.Join("", allowed) + "]"))).ToList();
Just another way to implement it.
I think you can use String.Trim Method (Char()) on each element , then the empty element is you want .
var arr = new string[] { "aabb", "aacc", "aaabbcc", "aabbbcc", "aabbccd" };
var arStr = new string[] { "a", "b", "c" };
var str = string.Join("", arStr);
var result = from p in arr
let arCharL = arStr.Select(a => Convert.ToChar(a)).ToArray()
let arCharR = p.ToCharArray()
where p.Trim(arCharL).Length == 0 && str.Trim(arCharR).Length == 0
select p;

LINQ expression for shortest common prefix

Can anyone help me with a nice LINQ expression for transforming a list of strings in another list containing only the shortest distinct common prefixes for the strings? The delimiter for prefixes is ..
Example: ["A", "A.B.D", "A", "A.B","E","F.E", "F","B.C"]
Goes to: ["A", "E", "F", "B.C"]
Removed:
"A.B.D" and "A.B" because the prefix "A" is already in the list
"A" because is duplicate
"F.E" because "F" already in list
Thanks!
Here you go:
from set in
(from item in list select item.Split('.')).GroupBy(x => x[0])
select
set.First()
.TakeWhile((part, index) => set.All(x => x.Length > index && x[index].Equals(part)))
.Aggregate((x, y) => String.Format("{0}.{1}", x, y));
By way of explanation:
First, we split all the strings by '.' and group by their first token.
Then, we look at the first element of each grouping, and we take parts from it while every element of that group continues to match (TakeWhile).
Then, we take all those parts and recompose them with the Aggregate(String.Format).
var items = new[] { "A", "A.B.D", "A", "A.B", "E", "F.E", "F", "B.C" };
var result = items
.OrderBy(s => s.Length)
.Distinct()
.ToLookup(s => s.Substring(0, 1))
.Select(g => g.First());
Order the items by their length, call distinct to remove duplicates, convert to groupings based on the first character, and select the first item in each group.
Yields:
"A", "E", "F", "B.C"
Edit: You probably don't even need Distinct as your selecting the first item in each group anyway, so it's really redundant.
EDIT: thanks to the comments for pointing out a bug in my earlier approach.
To get around that shortcoming this query should work:
var list = new List<string> { "A.B.D", "A", "A.B","E","F.E", "F","B.C", "B.C.D" };
var result = list.OrderBy(s => s)
.GroupBy(s => s[0])
.Select(g => g.First());
foreach (var s in result)
{
Console.WriteLine(s);
}
Incorrect approach:
The following query will group each string by the first character. Next, if the group count has more than one item the key is selected, otherwise the single item is selected.
var list = new List<string> { "A", "A.B.D", "A", "A.B", "E", "F.E", "F", "B.C" };
var result = list.GroupBy(s => s[0])
.Select(g => g.Count() > 1 ? g.Key.ToString() : g.Single());
foreach (var s in result)
{
Console.WriteLine(s);
}
Nailed it - assuming that if the source list contains "Q.X" & "Q.Y" then the result should contain "Q".
var source = new []
{
"A", "A.B.D", "A",
"A.B", "E", "F.E",
"F", "B.C",
"Q.X", "Q.Y",
"D.A.A", "D.A.B",
};
Func<string, int> startsWithCount =
s => source.Where(x => x.StartsWith(s)).Count();
var results =
(from x in source.Distinct()
let xx = x.Split('.')
let splits = Enumerable
.Range(1, xx.Length)
.Select(n => String.Join(".", xx.Take(n)))
let first = startsWithCount(splits.First())
select splits
.Where(s => startsWithCount(s) == first)
.Last()
).Distinct();
// results == ["A", "E", "F", "B.C", "Q", "D.A"]
string[] source = {"A", "A.B", "A.B.D", "B.C", "B.C.D", "B.D", "E", "F", "F.E"};
var result =
source.Distinct()
.Select(str => str.Split('.'))
.GroupBy(arr => arr[0])
.Select(g =>
{
return string.Join(".",
g.Aggregate((arr1, arr2) =>
{
return arr1.TakeWhile((str, index) => index < arr2.Length
&& str.Equals(arr2[index]))
.ToArray();
}));
});
Steps:
(1) Remove duplicated elements by Distinct()
(2) Split each element to an array, also get ready to be grouped
(3) Group those arrays by the first string in the array
(4) For each group, create one common prefix by aggregating all arrays in the group. The logic for aggregating is that for two arrays arr1 and arr2, take the elements in arr1 until (1)out of bounds (2) corresponding element in arr2 is different
Note: I add two return statements in the code, to make it look cleaner. It can be shorter if remove return and its {} brackets.
How about:
var possible = new List<string> { "A", "A.B.D", "A", "A.B", "E", "F.E", "F", "B.C" };
var shortest = possible.Distinct().Where(x => possible.Distinct().Where(y => !y.Equals(x) && x.StartsWith(y)).Count() == 0).ToList();
It checks the list against itself excluding items that are equal and any items that starts with any of the other items. I'm not sure about the effeciency though :)
I think it might be hard to solve with one single nice looking linq expression so I wrote a recursive function using linq that solves the problem:
class Program
{
static void Main(string[] args)
{
var input = new string[] { "A", "A.B.D", "A", "A.B", "E", "F.E", "F", "B.C", "B.C.D", "B.E" };
var output = FilterFunc(input);
foreach (var str in output)
Console.WriteLine(str);
Console.ReadLine();
}
static string[] FilterFunc(string[] input)
{
if (input.Length <= 1)
return input;
else
{
var firstElem = input[0];
var indexNr = firstElem.Length;
var maxFilteredElems = 0;
for (int i = firstElem.Length; i > 0; i--)
{
var numberOfFilteredElems = input.Where(x => x.StartsWith(firstElem.Substring(0, i))).Count();
if (numberOfFilteredElems > maxFilteredElems)
{
maxFilteredElems = numberOfFilteredElems;
indexNr = i;
}
}
var prefix = firstElem.Substring(0, indexNr);
var recursiveResult = FilterFunc(input.Where(x => !x.StartsWith(prefix)).ToArray());
var result = recursiveResult.ToList();
prefix = prefix.EndsWith(".") ? prefix.Substring(0, prefix.Length - 1) : prefix;
result.Insert(0, prefix);
return result.ToArray();
}
}
}
The code could probably be more effective and more organized but don't have time for that now. I think the other solutions are wrong so far, so that's why you get my longer one. I think you need to solve it recursively to be sure to get the shortest list.
My attempt, loop through items removing anything prefixed with another item.
static void Run()
{
var list = new string[] {"A", "A.B.D", "A",
"A.B", "E", "F.E",
"F", "B.C",
"Q.X", "Q.Y",
"D.A.A", "D.A.B"
};
int size = 0;
var prefixList = new string[list.Length];
Array.Copy(list, prefixList, list.Length);
for (int i = 0; i < list.Length; i++)
prefixList
= prefixList
.Where(c => !c.StartsWith(list[i]) || c == list[i])
.Distinct()
.ToArray();
foreach (string s in prefixList)
Console.WriteLine(s);
Console.ReadLine();
}
var list = new[] { "A.B.D", "A", "E", "A.B", "F", "F.E", "B.C.D", "B.C" };
var result = from s in list
group s by s.Split('.').First() into g
select LongestCommonPrefix(g);
foreach (var s in result)
{
Console.WriteLine(s);
}
Output:
A
E
F
B.C
Method to find longest common prefix from here (replace / with .).
My understanding of the question says a list containing both "B.C" and "B.E" but no "B" would get both "B.C" and "B.E".
string[] items = { "A", "A.B.D", "A", "A.B", "E", "F.E", "F", "B.C" };
char delimiter = '.';
var result = (from item in items.Distinct()
where !items.Any(other => item.StartsWith(other + delimiter))
select item).ToArray();
foreach (var item in result)
{
Console.WriteLine(item);
}
output
A
E
F
B.C
also works with multi-character prefixes
string[] items =
{
"Alpha",
"Alpha.Beta.Delta",
"Alpha",
"Alpha.Beta",
"Echo",
"Foxtrot.Echo",
"Foxtrot",
"Baker.Charlie"
};
gets
Alpha
Echo
Foxtrot
Baker.Charlie
If I strictly stick to the definition that dave provided, the answer is easier than it seems:
remove duplicates => distinct
remove any item that starts with any other item in the list
so we get:
from item in items.Distinct()
where !items.Any(other => other != item && item.StartsWith(other + '.'))
select item;
For the B.C and B.D question, this works as specified: Neither one includes the other, so none of the removing conditions mentioned by dave is triggered.
I admit that there might be more exciting anwers, but I'm afraid that's just not in the question ;)
Update: added delimiter to where clause in order to account for multi-char words. thanks svick!
var list = new List<string> { "A", "A.B.D", "A", "A.B", "E", "F.E", "F", "B.C" };
var result = (list.Select(a => a.Split('.').First())).Distinct();

Categories

Resources