Searching a list to get index values in c# - c#

I have a string comma separated list of some data. I have another list of strings of keywords that i want to search for in the first list. I want to have returned to me the index of all the elements in the first list that do no contain any of the keywords in the second list. For example:
List 1:
Student,101256,Active
Professor,597856,Active
Professor,697843,Inactive
Student,329741,Active
Student,135679,Inactive
Student,241786,Inactive
List 2:
697843
241786
My query on List 1 should be, give me all the index of all the elements that do not contain any of the elements of list 2. Therefore, the return list of indices should be 0,1,3,4. Is there any way to accomplish this?
Thanks in advance!
Edit: This is my try:
List<int> index = list1
.Select((s, i) => new { s, i })
.Where(e => !list2.Contains(e.s))
.Select(e => e.i).ToList();

You will need to reference System.Linq, this has now been edited to include the !Student filter
var list1 = new List<string> {
{"Student,101256,Active"},
{"Professor,597856,Active"},
{"Professor,697843,Inactive"},
{"Student,329741,Active"},
{"Student,135679,Inactive"},
{"Student,241786,Inactive"}
};
var list2 = new List<string> {{"697843"}, {"241786"}};
var result = list1
.Select((item,i)=> new {index=i,value=item})
.Where(item => !item.value.StartsWith("Student"))
.Where(item => !item.value.Split(',').Any(j => list2.Contains(j)))
.Select(item=>item.index)
.ToList();
The first select extracts the index before filtering, the pre-edited version calculated the index after the filter and so was incorrect.

Related

C#: Get double entries in string list

In C# I have a list of type string. This list contains strings with the length of 8. Now I need to find entries, where the characters from position 4 to 7 are the same and fill a second list with those entries. How would I do that?
Example content of existing list:
tmr523fw
tmr5287g
tmx523fu
tmy4741g
The new list should now contain those entries:
tmr523fw
tmx523fu
Linq GroupBy and Substring should do the job here
List<string> items = new List<string>() { "tmr523fw", "tmr5287g", "tmx523fu", "tmy4741g" };
List<string> result = items.GroupBy(x => x.Substring(3, 4))
.Where(x => x.Count() > 1)
.SelectMany(x => x)
.ToList();
assuming that double entries means the appearance x.Count() > 1

check if an array contains values of another array

I have two list, I want the values of list 1 if it contains any of value from list 2.
List<string> list1 = new List<string>();
list1.Add("Sunday is far away");
list1.Add("Today is Monday");
list1.Add("Tuesday is too near");
List<string> list2 = new List<string>();
list2.Add("Sunday");
list2.Add("Monday");
list2.Add("Tuesday");
var result1 = list1.Where(x => list2.Any(y => y.Contains(x))).ToList(); //no results
var result2 = list2.Where(x => list1.Any(y => y.Contains(x))).ToList(); //give values of list2. But I need values of list1
Update:
I need values of list1 in result, how can I get that?
Simple thing you missed, Take a look into the collection, All Items in the first list are larger than that of second, so the contains will return false. So you have to check for second item in first like the following:
Here is your modified code with result:
var result1 = list1.Where(x => list2.Any(y => x.Contains(y))).ToList();
var result2 = list2.Where(x => list1.Any(y => y.Contains(x))).ToList();
Simply you can. If List1 contains any value of List2 then result=List1. Otherwise null;
var result = list2.Any(l2 => list1.Contains(l2))==true?list1:null;

Sorting a dynamic object list based on another list

I have two lists. One is a dynamic list of objects. Another is a list of strings. I want to sort the object list based on the other list.
List<dynamic> List1; // Object1,Object2,Object3,Object4
List <String> List2; //"abc","bcd","da"
These objects has one of the attributes "alphabets" on whose basis it has to be sorted.
The objects may not be equal to number of elements in second list.
Something like this might work, if the indexes of the two lists align how you want them to. You'd have to ensure that the lists have the same length for this to work correctly though.
var result = list1
.Select((item, index) =>
new
{
Item = item,
Order = list2[index]
})
.OrderBy(x => x.Order)
.Select(x => x.Item);
If they aren't the same length, what would be the criteria for the order? That would be an undefined problem. One approach would be to put them at the end of the list.
var result = list1.Take(list2.Length)
.Select((item, index) =>
new
{
Item = item,
Order = list2[index]
})
.OrderBy(x => x.Order)
.Select(x => x.Item);
var concatted = result.Concat(list1.Skip(list2.Length));
Ok, assuming that List1 contains a list of objects, and each object contains an attribute called "alphabet", and you want to sort this list of objects, but the sort order is specified in List2 which has the possible values of alphabet in sorted order, then you could do this:
int i=0;
var List2WithRowNum = from str2 in List2.AsEnumerable() select new{ rowNum = i++, str2 };
var sortedList = from obj1 in List1.AsEnumerable()
join strKey in List2WithRowNum.AsEnumerable() on ((listObject)obj1).alphabet equals strKey.str2
orderby strKey.rowNum
select obj1;
sortedList would then be a list of your original objects (from List1) sorted by their "alphabet" attribute, in List2 order.

Query an XML using LINQ and excluding where an Attribute value is equal to that of an Element

I have a LINQ query against an XML, that gives me a list of nested lists, each sublist being a list of an elements("row") attributes.
var items = loadbodies.Descendants("row").Select(a => a.Attributes().Select(b => b.Value).ToList()).ToList();
This works as intended but, what I actually need to is query this against another list of values so as not to have sublists added where one of the elements attributes("messageID") is on the second list. I can do this for one value but need to check it against the entire second list.
The query to exclude a single sublist by a single hardcoded value from the second list is below.
var items = loadbodies.Descendants("row").Where(c => (string)c.Attribute("messageID") != "avaluefromthesecondlist").Select(a => a.Attributes().Select(b => b.Value).ToList()).ToList();
Any help would be much appreciated.
Just use Contains. Note that splitting lines helps readability considerably:
var ids = ...; // Some sequence of ids, e.g. a List<string> or HashSet<string>
var items = loadbodies
.Descendants("row")
.Where(row => ids.Contains((string) row.Attribute("messageId")))
.Select(a => a.Attributes()
.Select(b => b.Value)
.ToList())
.ToList();
Note that you could use a Join call too... but so long as you've got relatively few IDs, this should be fine.

how to get items between the search parameters

Work on C#.I have a list named as InputList .From this list I have to search Some string.After search I want to select all item between the search parameter.Bellow picture discribe in detail.
Text Input File:
Collection :
After read the textFile I store data in dataset then,convert the dataset as collection .From this collection i want to get valuse between the search parameters.
I write the bellow syntax but r3 result can not satisfy me.
var InputList = (from p in ds.Tables["InputFile"].Rows.Cast<DataRow>().ToArray() select p.ItemArray).ToList();
var r3 = (from c in InputList
where c.Any(e => e.ToString().Contains("Loading"))
select c).ToList();
If have any query plz ask.Thanks in advance.
To get the results between queries, the SkipWhile() and TakeWhile() would work (both have variants that give the index to the predicate), but I don't think that is quite what you want given your image.
var loadingIndexes = InputList.Select((r, i) => new { Row=row, Index=i })
.Where(x => x.Row.Any(e =>
e.ToString().Contains("Loading"))
.Select(x => x.Index);
var betweenLines = loadingIndexes
.Select(i => InputList
.Skip(i)
.TakeWhile(r => !r.Any(e =>
e.ToString().Contains("FULL")))
.ToList())
.ToList();
Here betweenLines is a List of Lists of DataRows, where each list is between a DataRow containing the string "Loading" (inclusive) and the next `DataRow" containing the string "FULL" (exclusive).

Categories