Linq Query to Compare with List of string values - c#

I need to compare and get the matching values from a string list with LINQ. Have a look at my code.
Code
Split = Id.Split(',');
List<string> uids = new List<string>(Split);
var model = (from xx in Db.ItemWeedLogs
where xx.ItemNo == uids
// I need to pass a string list to extract the matching record.
select xx).ToList();

Try this :
var model = (from xx in Db.ItemWeedLogs
where uids.Contains(xx.ItemNo)
select xx).ToList();

Try:
where uid.contains(xx.ItemNo)

I think this is much more faster and clear.
var model = Db.ItemWeedLogs
.Join(Id.Split(','), di => di.ItemNo, si => si, (d, s) => new {d})
.ToList();

Related

How do I put distinct values from a LINQ query into a list?

I've looked at several answers to similar questions, but none of them solve my problem. All I need to do is get distinct values from a LINQ query (that queries a XML file) and put them into a list. Here is what I have tried:
var XmlData = XDocument.Load("PathToFile");
List<string> XmlItems = new List<string>();
var XQuery = from m in XmlData.Root.Elements()
where m.Attribute("Category").Value.ToString().Equals("TheCategory")
select (m.Attribute("TheAttribute").Value).Distinct().ToString();
XmlItems.AddRange(XQuery);
foreach (var item in XmlItems)
{
ComboBoxTeams.Items.Add(item);
}
The Distinct() function call is not giving the expected result. I'm unfamiliar with how to get distinct values from a LINQ query. Any suggestions?
At this point, your Distinct
var XQuery = from m in XmlData.Root.Elements()
where m.Attribute("Category").Value.ToString().Equals("TheCategory")
select (m.Attribute("TheAttribute").Value).Distinct().ToString();
is only for (m.Attribute("TheAttribute").Value), not for the whole statement
You may need to change it to
var XQuery = from m in XmlData.Root.Elements()
where m.Attribute("Category").Value.ToString().Equals("TheCategory")
select (m.Attribute("TheAttribute").Value.ToString()); //get everything first, ToString probably needed
var XQueryDistinct = XQuery.Distinct(); //get distinct among everything you got
You have the .ToString() and .Distinct() in the wrong places.
var XmlData = XDocument.Load("PathToFile");
List<string> XmlItems = new List<string>();
var XQuery = from m in XmlData.Root.Elements()
where m.Attribute("Category").Value.ToString().Equals("TheCategory")
select (m.Attribute("TheAttribute").Value).Distinct().ToString();
XmlItems.AddRange(XQuery);
foreach (var item in XmlItems)
{
ComboBoxTeams.Items.Add(item);
}
becomes:
var XmlData = XDocument.Load("PathToFile");
var XmlItems = (from m in XmlData.Root.Elements()
where m.Attribute("Category").Value.ToString().Equals("TheCategory")
select (m.Attribute("TheAttribute").Value.ToString())).Distinct();
foreach (var item in XmlItems)
{
ComboBoxTeams.Items.Add(item);
}
If you have a list of simple values, you need to remove the use of Distinct in your select and put after.
var XQuery = (from m in XmlData.Root.Elements()
where m.Attribute("Category").Value.ToString().Equals("TheCategory")
select (m.Attribute("TheAttribute").Value.ToString())).Distinct();
If you have complex objects you have two alternatives:
Using morelinq you can use DistinctBy:
XmlItems.DistinctBy(x => x.WhateverProperty);
Otherwise, you can use a group:
XmlItems.GroupBy(x => x.idOrWhateverOtherProperty)
.Select(g => g.First());
You might try
var uniqueList = yourList.Distinct().ToList();
after you got your non-unique list.

List<comma-separated strings> => List<string>?

Trying to come up with a LINQy way to do this, but nothing's coming to me.
I have a List<> of objects which include a property which is a comma-separated list of alpha codes:
lst[0].codes = "AA,BB,DD"
lst[1].codes = "AA,DD,EE"
lst[2].codes = "GG,JJ"
I'd like a list of those codes, hopefully in the form of a List of strings:
result = AA,BB,DD,EE,GG,JJ
Thanks for any direction.
Use SelectMany to get all split codes and use Distinct to not repeat the values.
Try something like this:
var result = lst.SelectMany(x => x.codes.Split(",")).Distinct().ToList();
You need to use Split to split each string into multiple strings. Then you need to use SelectMany to concatenate multiple sequences into a single sequence, and then you need to use Distinct to remove duplicates.
var result =
lst
.SelectMany(x => x.codes.Split(','))
.Distinct()
.ToList();
if you need a string as a result:
string result = string.Join(",",lst.SelectMany(p=>p.codes.Split(",")).Distinct());
Try this:
List<string> list = new List<string>();
char[] sep = new char[1];
sep[0] = ',';
foreach (string item in lst)
{
list.AddRange(item.Split(sep));
}
list = list.Distinct().ToList();

How can I use linq to search inside a list of objects

I am new in linq and I want to use it in a list without use a foreach. How can I return a list from a list of objects List<House> where house ha swimming pool.
Class Houses
{
Int Id,
bool HasSwimmingPool
...
}
All you need is Where method, which filters collection based of given predicate:
var results = source.Where(x => x.HasSwimmingPool).ToList();
Additional ToList() call makes the results List<House> instead of IEnumerable<House>.
You can achieve the same using syntax-based query:
var results = (from h in source
where h.HasSwimmingPool
select h).ToList();
That is simple:
var yourCollection = new List<Houses>();
var housesThatHasASwimmingPool = yourCollection.Where(s => s.HasSwimmingPool);
try this:
var swimmngHomes = listOfHouses.
Where( h => h.HasSwimmingPool == true);
List<Houses> housesWithPools = oldHouses.Where(x => x.HasSwimmingPool== true);

List of two attributes in same class

I have an Entity Class called Session and it containts two attributes: LecturerOne and LectureTwo. I want to create a union of all the distinct names in LecturerOne and LecturerTwo:
I got just LecturerOne working.
public List<string> ListLecturer()
{
var lecturerNames = (from s in db.Sessions
select s.LecturerOne).Distinct();
List<string> lecturerList = lecturerNames.ToList();
return lecturerList;
}
One option:
var list = db.Sessions.SelectMany(s => new string[] { s.LecturerOne,
s.LecturerTwo })
.Distinct()
.ToList();
I don't know offhand how EF will treat that, but it's worth a try...
Alternatively, similar to Jamiec's answer but IMO simpler:
var list = db.Sessions.Select(s => s.LecturerOne)
.Union(db.Sessions.Select(s => s.LecturerTwo))
.ToList();
(Union already returns distinct results, so there's no need to do it explicitly.)
var lecturerOnes = (from s in db.Sessions
select s.LecturerOne);
var lecturerTwos = (from s in db.Sessions
select s.LecturerTwo);
List<string> lecturerList = lecturerOnes.Union(lectureTwos).ToList();

Get records which do not start with an alphabetical character in linq

I need to get a list of records that do not start with an alphabetical character, i.e. which either starts with a numerical character or any special character.
Whats the simple LINQ query to get this list?
List<string> Entries = new List<string>();
Entries.Add("foo");
Entries.Add("bar");
Entries.Add("#foo");
Entries.Add("1bar");
var NonAlphas = (from n in Entries
where !char.IsLetter(n.ToCharArray().First())
select n);
For Linq-to-sql you could hydrate your retrieval from the database by by enumerating the query (call ToList). From that point on, your operations will be against in-memory objects and those operations will not be translated into SQL.
List<string> Entries = dbContext.Entry.Where(n => n.EntryName).ToList();
var NonAlphas = Entries.Where(n => !char.IsLetter(n.First()));
Something like this?
List<string> lst = new List<string>();
lst.Add("first");
lst.Add("second");
lst.Add("third");
lst.Add("2abc");
var result = from i in lst where !char.IsLetter(i[0]) select i;
List<string> output = result.ToList();
Edit: I realized that using Regex here was overkill and my solution wasn't perfect anyway.
string[] x = new string[3];
x[0] = "avb";
x[1] = "31df";
x[2] = "%dfg";
var linq = from s in x where !char.IsLetter(s.ToString().First()) select s;
List<string> simplelist = new List<string>(linq);
/* in simple list you have only "31df" & "dfg" */
One thing to note is that you don't need to convert the string to a chararray to use linq on it.
The more consise version would be:
var list = new List<string> {"first","third","second","2abc"};
var result = list.Where(word => !char.IsLetter(word.First()));

Categories